使用tkinter按钮时遇到问题。我使用for name in list_of_namebuttons
创建6个按钮(list_of_namebuttons中有6个名称),并且按钮创建正确。但是,当我尝试按一个按钮以获取该按钮的名称时,无论按第一个,第三个还是最后一个按钮,我都只会得到最后一个按钮的名称。
edit1:如何实现列表并附加这些按钮,以使参考返回? 如何在不使用部分功能的情况下实现此功能?(并且不要在其他线程中使用类似的解决方案)
这是我用来创建按钮的代码,以及试图获取相同按钮名称的函数。
我试图在函数内部使用for循环来查找按钮文本:
def Modulo_6M(self): #cria os botoes de 6M
tk.Label(self.frame_6M).pack(side="top", fill="both", expand=True)
self.list_buttons = ["METODO", "MÃO DE OBRA", "MATERIA PRIMA", "MAQUINA", "MEDIÇÃO", "MEIO AMBIENTE"]
for name in self.list_buttons:
self.sixM_button = tk.Button(self.frame_6M)
self.sixM_button["text"] = name
self.sixM_button["height"] = 2
self.sixM_button["width"] = 10
self.sixM_button["bg"] = color_blue
self.sixM_button["fg"] = "white"
self.sixM_button["activebackground"] = color_dgreen
self.sixM_button["activeforeground"] = "white"
self.sixM_button["font"] = self.font_main
self.sixM_button["command"] = self.func_6M ###########################################
self.sixM_button["state"] = "normal" # normal, disabled or active
self.sixM_button.pack(side="left", expand=True)
def func_6M(self):
#print(self.sixM_button.cget('text'))
for name in self.list_buttons:
if self.sixM_button["text"] == name:
self.sixM_button["state"] = "active"
self.sixM_button["relief"] = "sunken"
print(self.sixM_button["text"])
return self.sixM_button["text"]
我现在想在该按钮内打印文本,稍后我想将此相同的信息存储在变量中以便在csv文件中编写。
edit2:这是解决方案
def Modulo_6M(self): #cria os botoes de 6M
tk.Label(self.frame_6M).pack(side="top", fill="both", expand=True)
self.list_buttons = ["METODO", "MÃO DE OBRA", "MATERIA PRIMA", "MAQUINA", "MEDIÇÃO", "MEIO AMBIENTE"]
self.buttons = []
for name in self.list_buttons:
self.sixM_button = tk.Button(self.frame_6M)
self.sixM_button["text"] = name
self.sixM_button["height"] = 2
self.sixM_button["width"] = 10
self.sixM_button["bg"] = color_blue
self.sixM_button["fg"] = "white"
self.sixM_button["activebackground"] = color_dgreen
self.sixM_button["activeforeground"] = "white"
self.sixM_button["font"] = self.font_main
self.sixM_button["command"] = partial(self.func_6M, name)
self.sixM_button["state"] = "normal" # normal, disabled or active
self.sixM_button.pack(side="left", expand=True)
self.buttons.append(self.sixM_button)
def func_6M(self, text_inside_button):
for button in self.buttons:
button["relief"] = "raised"
button["bg"] = color_blue
for button in self.buttons:
if button["text"] == text_inside_button:
button["bg"] = color_dgreen
button["relief"] = "sunken"
print(text_inside_button)
return text_inside_button