2015-09-26 88 views
1

我是tKinter的新手。我試過這個代碼,它不起作用。當我點擊任何按鈕時(是/否),對話框不會關閉,打印語句也不打印 。我知道在Swing中我需要事件來打印這個聲明。 tKinter是否一樣?tKinter對話框按鈕沒有響應

from tkinter import * 
import tkinter.messagebox 

root = Tk() 

answer=tkinter.messagebox.askquestion('Question','what is your name?') 
if answer=='Yes': 
print('I am King') 

root.mainloop() 

我該如何去改正它?

回答

0

返回的值將是'yes'(全部小寫),但您試圖將其與'Yes'進行覈對,因此它不會打印。嘗試使用'yes'來檢查它。

此外,實際的應用程序root不會關閉,直到您點擊x按鈕,因爲您正在定義Tk()應用程序並進入其主循環。如果您希望它關閉(並且程序以打印語句結束),那麼您不需要root=Tk()root.mainloop()

示例 -

import tkinter.messagebox 

answer=tkinter.messagebox.askquestion('Question','what is your name?') 
if answer=='yes': 
    print('I am King') 

請注意,這將打印'I am King'到控制檯。


要回答在評論這個問題 -

有沒有一種方法,我可以隱藏叫tk--這是第二個在後臺的對話框?

您必須使用Tk()創建應用程序,然後才能使用root.withdraw()。示例 -

import tkinter.messagebox 
from tkinter import Tk 

root = Tk() 
root.withdraw() 
answer=tkinter.messagebox.askquestion('Question','what is your name?') 
if answer=='yes': 
    print('I am King') 
+0

有沒有一種方法可以隱藏名爲tk--這是第二個在後臺的對話框? – BattleDrum

+0

@BattleDrum我已經添加了一個解決方案,你可以現在檢查。 –

1

您必須在'if'語句下使用縮進。 I.e:

if answer.lower() == 'yes': # this proofs against mistakes with user capitalisation 
     print ('I am the king')