2013-12-15 269 views
2

我是Python的新手,我試圖使用Tkinter創建一個簡單的應用程序。在Tkinter中單擊後禁用按鈕

def appear(x): 
    return lambda: results.insert(END, x) 

letters=["A", "T", "D", "M", "E", "A", "S", "R", "M"] 

for index in range(9): 
    n=letters[index] 
    nButton = Button(buttons, bg="White", text=n, width=5, height=1, 
    command =appear(n), relief=GROOVE).grid(padx=2, pady=2, row=index%3, 
    column=index/3) 

我想要做的就是禁用按鈕,一旦我點擊它們。 我試圖

def appear(x): 
    nButton.config(state="disabled") 
    return lambda: results.insert(END, x) 

但它給我下面的錯誤:

NameError: global name 'nButton' is not defined

回答

2

這裏有幾個問題:

  • 只要你創建的小部件動態地,您需要將對它們的引用存儲在集合中,以便稍後可以訪問它們。

  • Tkinter小部件的grid方法始終返回None。所以,你需要在自己的線路上撥打grid。當你分配一個按鈕的command選項需要參數的函數

  • ,你必須使用一個lambda或這樣的「隱藏」功能的該呼叫按鈕被點擊,直到。有關更多信息,請參閱https://stackoverflow.com/a/20556892/2555451

  • 下面是一個示例腳本解決所有這些問題:

    from Tkinter import Tk, Button, GROOVE 
    
    root = Tk() 
    
    def appear(index, letter): 
        # This line would be where you insert the letter in the textbox 
        print letter 
    
        # Disable the button by index 
        buttons[index].config(state="disabled") 
    
    letters=["A", "T", "D", "M", "E", "A", "S", "R", "M"] 
    
    # A collection (list) to hold the references to the buttons created below 
    buttons = [] 
    
    for index in range(9): 
        n=letters[index] 
    
        button = Button(root, bg="White", text=n, width=5, height=1, relief=GROOVE, 
            command=lambda index=index, n=n: appear(index, n)) 
    
        # Add the button to the window 
        button.grid(padx=2, pady=2, row=index%3, column=index/3) 
    
        # Add a reference to the button to 'buttons' 
        buttons.append(button) 
    
    root.mainloop()