所以我想将整个程序中的所有tk.Button(和条目)对象添加到列表中。 (这样我可以通过迭代和配置来改变每个按钮的颜色)
我正在创建一堆像这样的tkinter帧:
class AppClass(tk.Tk):
def __init__(self, *args, **kwargs):
# Initialising Tkinter
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, 'test-program')
tk.Tk.geometry(self, '800x480')
container = tk.Frame(self)
container.pack(fill='both', expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.background_theme = '2'
self.background_theme_to_be_written_to_file = '2'
self.frames = {}
for F in (HomePage,
SecondName,
ThirdName):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
frame.configure(background=background_page)
self.show_frame(HomePage)
app = AppClass()
app.mainloop()
app = None
exit()
想法?我知道 .winfo_children()
可以选择页面中的所有对象 - 我们可以选择程序中的所有对象吗?
**
目前我正在尝试制作类似这样的作品 - 奇怪的是它只改变了屏幕上的一个按钮(有4个):
parent.list_of_objects_in_parent = tk.Button.winfo_children(parent)
print(parent.list_of_objects_in_parent)
for entry in parent.list_of_objects_in_parent:
entry.config(bg="pink")
**快速更新:
我有一个部分解决方案:
self.bind("<<ShowFrame>>", self.on_show_frame)
...
def on_show_frame(self, event):
self.list_of_objects_in_parent = tk.Button.winfo_children(self)
print(self.list_of_objects_in_parent)
for entry in self.list_of_objects_in_parent:
if type(entry) == type(self.button_to_go_to_home_page):
entry.config(bg="pink")
print("working")
答案 0 :(得分:4)
是的,这是可能的。
您只需在.winfo_children()
窗口上调用Tk()
,该窗口将返回窗口顶层窗口中可以迭代的所有窗口小部件列表,如下所示:
from tkinter import *
root = Tk()
def command():
for i in root.winfo_children():
i.configure(bg="pink")
entry = Entry(root)
button = Button(root, text="Ok", command=command)
entry.pack()
button.pack()
root.mainloop()
如果您有多个小部件层(IE,Frame
包含小部件,Toplevel
小部件),那么您需要添加某种递归才能获得所有对于程序中的小部件,我们可以使用以下内容执行此操作:
from tkinter import *
root = Tk()
def command():
x = root.winfo_children()
for i in x:
if i.winfo_children():
x.extend(i.winfo_children())
i.configure(bg="pink")
entry = Entry(root)
button = Button(root, text="Ok", command=command)
frame = Frame(root)
entry2 = Entry(frame)
top = Toplevel(root)
entry3 = Entry(top)
entry.pack()
entry2.pack()
entry3.pack()
button.pack()
frame.pack()
root.mainloop()