2017-05-15 49 views
0

我有這個遊戲,你需要選擇文本,而不是它的顏色是:如何從python中的tkinter獲取按鈕輸入?

import tkinter, os, random 

colors = ['Green', 'Red', 'Blue','Yellow', 'Pink', 'Orange', 'Purple', 'Grey', 'Brown', 'Black'] 

window = tkinter.Tk() 
os.chdir(os.path.dirname(os.path.abspath(__file__))) 

def color(color): 
    colors.remove(color) 
    text = random.choice(colors) 
    label = tkinter.Label(window, text=color, fg = text, highlightthickness = 20) 
    label.config(font=("Calibri", 44)) 
    buttonT = tkinter.Button(window, text=text) 
    buttonF = tkinter.Button(window, text=color) 
    colors.append(color) 
    label.pack() 
    buttonT.pack() 
    buttonF.pack() 

os.chdir(os.path.dirname(os.path.abspath(__file__))) 

window.title('Color Game') 
window.geometry('250x250') 
instructions = tkinter.Label(window, text = 'Select word, not color!') 
instructions.pack() 
window.iconbitmap('icon.ico') 
color(random.choice(colors)) 

window.mainloop() 

它生產這個窗口: enter image description here

如何檢查哪個按鈕以便用戶點擊以確定他的答案是否正確?你能指定我應該如何在你的代碼中實現你的答案嗎?它是如何工作的?

在此先感謝。

  • 斯塔夫羅斯
+0

@BillalBEGUERADJ是的。我該怎麼做,我該如何在我的代碼中實現它? – Smich

+0

@BillalBEGUERADJ謝謝! – Smich

+0

@StavrosMichalovits請檢查我的答案。我已經更新了它,並在代碼中添加了lambda函數。 –

回答

3

可以使用lambda函數這一點。

def populateMethod(self, method): 
    print "method:", method 

for method in ["Red","Green","Blue"]: 
    button = Button(window, text=method, 
     command=lambda m=method: self.populateMethod(m)) 

UPDATE:

我修改了代碼,增加了lambda函數。檢查並讓我知道它是否正常工作。

import tkinter, os, random 

colors = ['Green', 'Red', 'Blue','Yellow', 'Pink', 'Orange', 'Purple', 'Grey', 'Brown', 'Black'] 

window = tkinter.Tk() 
os.chdir(os.path.dirname(os.path.abspath(__file__))) 


def populateMethod(method): 
    print ("method:", method) 

def color(color): 
    colors.remove(color) 
    text = random.choice(colors) 
    label = tkinter.Label(window, text=color, fg = text, highlightthickness = 20) 
    label.config(font=("Calibri", 44)) 
    buttonT = tkinter.Button(window, text=text,command=lambda m=text: populateMethod(m)) 
    buttonF = tkinter.Button(window, text=color,command=lambda m=color: populateMethod(m)) 
    colors.append(color) 
    label.pack() 
    buttonT.pack() 
    buttonF.pack() 

os.chdir(os.path.dirname(os.path.abspath(__file__))) 

window.title('Color Game') 
window.geometry('250x250') 
instructions = tkinter.Label(window, text = 'Select word, not color!') 
instructions.pack() 
# window.iconbitmap('icon.ico') 
color(random.choice(colors)) 

window.mainloop() 
+0

謝謝。我一回家就會嘗試。我在學校。 – Smich

+0

當然@StavrosMichalovits –

1

你應該在按鈕使用命令參數,如:

def callback(): 
    print('button t clicked') 

buttonT = tkinter.Button(window, text=text, command=callback) 
+0

如何在我的代碼中實現此功能,以及它如何工作? – Smich