複数のコマンドを Tkinter ボタンにバインドする方法
Jinku Hu
2020年6月25日
2019年12月12日
Tkinter
Tkinter Button

このチュートリアルでは、複数のコマンドを Tkinter ボタンにバインドする方法を説明ます。ボタンをクリックすると、複数のコマンドが実行されます。
複数のコマンドを Tkinter ボタンにバインド
Tkinter ボタンには command
プロパティが 1つしかないため、複数のコマンドまたは関数を組み合わせて、この単一の関数をボタンの command
にバインドする必要があります。
次のよう lambda
に複数のコマンドを組み合わせて使用できます。
command=lambda:[funcA(), funcB(), funcC()]
この lambda
関数は、それぞれ funcA
、funcB
と、funcC
を実行します。
labmda
複数のコマンドのバインドの例
try:
import Tkinter as tk
except:
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('200x100')
self.button = tk.Button(self.root,
text = 'Click Me',
command=lambda:[self.funcA(), self.funcB(), self.funcC()])
self.button.pack()
self.labelA = tk.Label(self.root, text="A")
self.labelB = tk.Label(self.root, text="B")
self.labelC = tk.Label(self.root, text="C")
self.labelA.pack()
self.labelB.pack()
self.labelC.pack()
self.root.mainloop()
def funcA(self):
self.labelA["text"] = "A responds"
def funcB(self):
self.labelB["text"] = "B responds"
def funcC(self):
self.labelC["text"] = "C responds"
app = Test()
[
関数を 1つの単一関数に結合する
def combineFunc(self, *funcs):
def combinedFunc(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combinedFunc
上記の関数は、関数内の関数を定義し、関数オブジェクトを返します。
for f in funcs:
f(*args, **kwargs)
関数 combineFunc
の括弧内のすべての関数を実行します。
try:
import Tkinter as tk
except:
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('200x100')
self.button = tk.Button(self.root,
text = 'Click Me',
command = self.combineFunc(self.funcA, self.funcB, self.funcC))
self.button.pack()
self.labelA = tk.Label(self.root, text="A")
self.labelB = tk.Label(self.root, text="B")
self.labelC = tk.Label(self.root, text="C")
self.labelA.pack()
self.labelB.pack()
self.labelC.pack()
self.root.mainloop()
def combineFunc(self, *funcs):
def combinedFunc(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combinedFunc
def funcA(self):
self.labelA["text"] = "A responds"
def funcB(self):
self.labelB["text"] = "B responds"
def funcC(self):
self.labelC["text"] = "C responds"
app = Test()
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn