制作可被多个按钮使用的功能

时间:2018-09-10 01:57:25

标签: python function button tkinter

只是想知道是否有办法使它能够影响多个小部件。我想发生的是,当我单击一个按钮时,使用该功能它将从红色变为绿色;

def colour_change():
   self.configure(bg="green")

button1 = Tk.Button(self, bg="red")
button1.pack()
button2 = Tk.Button(self, bg="red)
button2.pack()

例如,当您按下按钮1时,它应该从红色变为绿色。按钮2相同。我知道我可以使用单独的功能来执行此操作,但是无论如何,我可以在同一功能中执行此操作吗?

1 个答案:

答案 0 :(得分:1)

以某种方式,您的函数需要确定调用它的小部件;一种方法是传递引用小部件的参数。在以下示例中,调用命令时将传递包含小部件的列表的索引:

import tkinter as tk


def colour_change(which_button):
    if buttons[which_button]['fg'] == 'red':
        buttons[which_button].configure(fg="blue")
    else:
        buttons[which_button].configure(fg="red")

root = tk.Tk()

button1 = tk.Button(root, text='button 1', fg="red", command=lambda: colour_change(0))
button1.pack()
button2 = tk.Button(root, text='button 2', fg="red", command=lambda: colour_change(1))
button2.pack()

buttons = [button1, button2]

root.mainloop()
相关问题