我正在通过此函数创建一组按钮:
from tkinter import *
from random import randint
window = Tk()
window.title("Test")
window.geometry('200x200')
color = ["red","blue","green","yellow","black","purple","orange"]
RandInt = 0
j = 0
h = 0
def ButtonDef(xvar = 0,yvar = 0):
btn = Button(command =lambda:[RandomColor()])
btn.grid()
btn.place(x = xvar*50, y = yvar*50, width = 50, height = 50)
def RandomColor():
RandInt = randint (0,6)
btn.configure(bg = color[RandInt])
while j in range (4):
i = 0
j += 1
while i in range (4):
ButtonDef(i,h)
i += 1
if i == 4:
h += 1
window.mainloop()
但是,我的 RandomColor()
函数仅更改我按下的按钮的颜色 - 这也很有趣,但我想知道如何让它随机更改 所有按钮。当由函数创建时,我会猜测创建的所有按钮都被命名为“btn”,因为这是我给它们的唯一名称。
我如何处理一组按功能创建的按钮中的所有(或一个特定)按钮? 或者简单地说,所有这些按钮的名称是什么?他们有共同的名字“btn”吗?他们被分配了一个隐藏的 ID 吗?
最佳答案
问题背后的原因:
问题是,当执行此行时: btn = Button(command =lambda:[RandomColor()])
在循环结束时,您仅获得对最后一个按钮的引用这是创建的。您失去了对其他按钮的引用。
解决方案:
如果您依靠 winfo_children()
就可以克服这个问题.
您必须执行 2 个步骤才能解决您的问题:
首先,将 btn = Button(command =lambda:[RandomColor()])
更改为 btn = Button(window, command=lambda:[RandomColor()])
。这仅仅意味着我们将每个创建的按钮附加到名为 window
的父窗口小部件。
那么您需要更改的是 RandomColor()
函数体,如下所示:
def RandomColor():
for child in window.winfo_children():
child.configure(bg=color[randint(0,6)])
演示:
这解决了您的问题,但您的代码不干净。您可以在 Code Review 上寻求改进代码的建议网站。
编辑:
这是针对您在评论中描述的场景的解决方案。
请注意,我必须从头开始创建更干净的代码(我知道你今天才开始,所以我不会责怪你)。在此代码中,我保留了我创建的每个按钮的引用:
import tkinter as tk
import random
class ChangeBottomRightColor(tk.Frame):
def __init__(self, master):
self.master = master
tk.Frame.__init__(self, self.master)
self.__colors = ["red","blue","green","yellow","black","purple","orange"]
self.configure_gui()
self.create_widgets()
def configure_gui(self):
pass
def create_widgets(self):
self.create_buttons()
def create_buttons(self):
self.buttons = {}
c = 0
for i in range(4):
for j in range(4):
self.buttons['button{}'.format(c)] = tk.Button(self.master)
self.buttons['button{}'.format(c)].grid(row=i, column=j)
self.buttons['button{}'.format(c)].config(width=3, height=3)
self.buttons['button{}'.format(c)].config(command=self.change_bottom_right_button_color)
c += 1
def get_random_color(self):
return random.choice(self.__colors)
def change_bottom_right_button_color(self):
self.buttons['button{}'.format(15)].config(bg=self.get_random_color())
if __name__ == '__main__':
root = tk.Tk()
main_app = ChangeBottomRightColor(root)
root.mainloop()
演示:
关于Python Tkinter - 由函数创建的对象的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50344006/