【问题标题】:Change properties of tkinter frame, from outside the frame从框架外部更改 tkinter 框架的属性
【发布时间】:2013-10-03 09:48:36
【问题描述】:

如何处理在当前函数之外创建的 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

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

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

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

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

    【讨论】:

    • 啊! (耶!但是 啊!)我为此奋斗了 小时。 非常感谢。
    猜你喜欢
    • 2015-04-28
    • 2021-05-29
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多