1
如何在當前函數外部創建的tkinter窗口部件上作用?下面的print
聲明顯示框架名稱存在,但我如何獲得它們?從框架外部改變tkinter框架的屬性
目標是在按下按鈕時更改背景和前景色等屬性。下面的例子中只顯示一個按鈕。實際應用中還有多個框架可供使用。
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
啊! (Yay!,但是* argh!*)我與這個**打了**。**非常感謝。 –