1

現在の関数の外で作成された tkinter ウィジェットにどのように作用しますか? 以下のprintステートメントは、フレーム名が存在することを示していますが、どうすれば取得できますか?

目標は、ボタンが押されたときに背景色や前景色などの属性を変更することです。以下の例では、ボタン 1 のみが示されています。また、実際のアプリケーションでは複数のフレームが使用されています。

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
4

1 に答える 1

2

必要なのは、作成時に f1 への参照を保存することだけです。

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

それができたら、それをself.f1クラス内で参照します。.

于 2013-10-03T10:59:00.577 に答える