2015-10-28 104 views
0

對於屏幕上的鍵盤,我需要26個按鈕,將鍵盤的一個字母添加到一個字符串。我得到的第一個問題是,按下按鈕後字符串不會被保存。例如,用戶按下'A','A'被打印並且應該被存儲。用戶現在按下'B','B'被打印並且'A'消失。第二個問題是該按鈕僅在第一次執行該功能。我的代碼所以下面遠了:按鈕excecu命令一次(Tkinter)

window = Tk() 
window.attributes('-fullscreen', True) 
window.configure(background='yellow') 
master = Frame(window) 
master.pack() 

e = Entry(master) 
e.pack() 
e.focus_set() 

nieuw_station = "" 

def printanswer(): 
    global nieuw_station 
    nieuw_station = e.get() 
    print(nieuw_station) 
    gekozen_station(nieuw_station) 


invoeren = Button(master, text="Invoeren", width=10, command=printanswer) 
invoeren.pack() 

def letter_toevoegen(nieuw_station, letter): 
    nieuw_station += letter 
    print(nieuw_station) 
    return nieuw_station 

a = Button(master, text="A", width=1, command=letter_toevoegen(nieuw_station, "a")) 
a.pack() 

b = Button(master, text="B", width=1, command=letter_toevoegen(nieuw_station, "b")) 
b.pack() 

window.mainloop() 

預期結果將是:用戶按下「A」,「A」得到印刷&存儲。現在用戶按'B','AB'打印&存儲。最後用戶按'C','ABC'現在打印&存儲。無論何時用戶按下'invoeren'按鈕,它都會以新字符串作爲參數發送到下一個函數(這實際上有效)。

回答

0

你有幾個問題。首先,command希望您通過函數,但您傳遞的函數的返回值爲。一個解決辦法是把它包在lambda

a = Button(master, text="A", width=1, command=lambda: letter_toevoegen(nieuw_station, "a")) 
a.pack() 

其次,我不知道是什麼nieuw_station.close()nieuw_station.open()正在做的 - 字符串沒有這些方法。

第三,字符串是不可變的,所以當你做nieuw_station += letterletter_toevoegen時,這個改變不會持續在函數之外。

實際得到它的一種方法是使用global nieuw_station - 然後你可能無法將它傳遞給函數。


隨着中說,9倍的10,當你看到一個global聲明,有使用類更好的辦法。在這裏,我們可以創建一個添加按鈕並跟蹤狀態的類。

class App(object): 
    def __init__(self): 
     self.nieuw_station = '' 

    def add_buttons(self): 
     a = Button(master, text="A", width=1, command=lambda: self.letter_toevoegen("a")) 
     a.pack() 
     # ... 

    def letter_toevoegen(self, letter): 
     time.sleep(2) 
     self.nieuw_station += letter 
     print(self.nieuw_station) 
     return self.nieuw_station 

。當然,我們會在這裏補充printanswer以及添加「打印答案」按鈕,等的代碼使用類看起來是這樣的:

app = App() 
app.add_buttons() 
window.mainloop() 

有這裏有很多變體,你會看到四處流動。 (有些人喜歡App繼承tkinter.Tk或其他一些tkinter小部件,其他人會通過父小部件到類,以便它可以知道在哪裏附加所有的元素,等等)點試圖 show是如何使用類作爲數據的容器而不是全局名稱空間。

+0

肯定不知道。要嘗試這種方式,謝謝你!很好的深入解釋btw! –