是否可以在仅一个Frame的内容上使用.tk_setPalette()?

时间:2014-07-14 19:40:48

标签: python tkinter

我有一个带有几个框架的根,每个框架都有标签。

  1. 我为root设置了前景和背景,
  2. 然后希望为一个所选框架的所有孩子设置特定的前景和背景。
  3. 我没有设法仅对一个帧进行更改,更改会传播到所有帧。

    以下代码就是一个例子。

    import Tkinter as tk
    
    class MyApp():
        def __init__(self):
            self.root = tk.Tk()
            # this frame content will be modified
            self.frame = tk.Frame(self.root)
            self.frame.grid(row=0, column=0)
            self.a = tk.Label(self.frame, text="hello world", font=("Arial", 100))
            self.a.grid(row=0, column=0)
            # this frame content will not change
            self.frame2 = tk.Frame(self.root)
            self.frame2.grid(row=1, column=0)
            self.a2 = tk.Label(self.frame2, text="bazinga", font=("Arial", 100))
            self.a2.grid(row=0, column=0)
            self.root.bind('q', self.toggle)
    
        def toggle(self, event):
            # go through all children (= Labels) of the first frame
            for children in self.frame.children.values():
                children.tk_setPalette(background="black", foreground="blue")
                children.configure()
    
    app = MyApp()
    app.root.mainloop()
    

    通话时,未设置颜色:

    enter image description here

    当按q时,我希望仅通过self.frame中的标签,并更改上标签颜色。事实并非如此:

    enter image description here

    我该怎么做才能更新一个选定框架的子项的颜色?

1 个答案:

答案 0 :(得分:2)

您不应该使用tk_setPalette方法。而是使用configure method

children.configure(background="black", foreground="blue")

另请注意,如果您愿意,可以更简洁地编写以上内容:

children.config(bg="black", fg="blue")