从框架外部更改tkinter框架的属性

时间:2013-10-03 09:48:37

标签: python tkinter

如何对在当前函数之外创建的tkinter小部件执行操作?下面的print语句显示帧名称存在,但我如何找到它们?

目标是在按下按钮时更改背景和前景色等属性。只有按钮一,如下例所示。在实际应用中还有多个帧正在运行。

from tkinter import *
ALL=N+S+W+E

class Application(Frame):
    def create_buttons(self):
        self.b = Button(self, text='Green',
            command=lambda: self.set_text_color('Green'))
        self.b.grid(row=1, column=1, sticky=ALL)
        #...

    def set_text_color(self, color):
        print("Setting text color", self, color)
        ## none of these work as frame_1 doesn't exist here
        ## how to act on a frame up the tree?
        #self.frame_1.config({'bg':color})
        #top.frame_1.config({'bg':color})
        #app.top.frame_1.config({'bg':color})
        #app.f1.config({'bg':color})
        f1.config({'bg':color})

    def __init__(self, master=None):
        Frame.__init__(self, master, padx=10, pady=10, name='top')
        self.config({'bg':'bisque'})
        self.rowconfigure(0, minsize=50, weight=1)
        self.grid(sticky=ALL)

        f1 = Frame(self, padx=10, pady=10, name='frame_1')
        f1.config({'bg':'cornsilk'})
        f1.rowconfigure(0, minsize=20, weight=1)
        f1.grid(sticky=ALL, columnspan=2)

        #...

        self.create_buttons()

root = Tk()
app = Application(master=root)
app.mainloop()

单击[绿色]按钮的结果:

Setting text color .top Green
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python32\lib\tkinter\__init__.py", line 1456, in __call__
    return self.func(*args)
  File "B:\py2\09\xx-set-color.py", line 7, in <lambda>
    command=lambda: self.set_text_color('Green'))
  File "B:\py2\09\xx-set-color.py", line 19, in set_text_color
    f1.config({'bg':color})
NameError: global name 'f1' is not defined

1 个答案:

答案 0 :(得分:2)

您需要做的就是在创建时保存对f1的引用:

def __init__(self, master=None):
    ...
    self.f1 = Frame(...)
    ...

一旦你这样做,你在课堂上将其称为self.f1