[英]Tkinter askquestion dialog box
我一直在嘗試將 askquestion 對話框添加到 Tkinter 中的刪除按鈕。 Curently 我有一個按鈕,一旦按下它就會刪除文件夾的內容 我想添加一個是/否確認問題。
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def deleteme():
tkMessageBox.askquestion("Delete", "Are You Sure?", icon='warning')
if 'yes':
print "Deleted"
else:
print "I'm Not Deleted Yet"
B1 = Tkinter.Button(top, text = "Delete", command = deleteme)
B1.pack()
top.mainloop()
每次我運行它時,即使我按“否”,我也會得到“已刪除”的聲明。 是否可以將 if 語句添加到 tkMessageBox 中?
問題是你的if
語句。 您需要從對話框中獲取結果(將是'yes'
或'no'
)並與之進行比較。 請注意下面代碼中的第 2 行和第 3 行。
def deleteme():
result = tkMessageBox.askquestion("Delete", "Are You Sure?", icon='warning')
if result == 'yes':
print "Deleted"
else:
print "I'm Not Deleted Yet"
現在關於為什么您的代碼似乎有效:在 Python 中,可以在需要布爾值的上下文中使用大量類型。 所以例如你可以這樣做:
arr = [10, 10]
if arr:
print "arr is non-empty"
else:
print "arr is empty"
字符串也會發生同樣的事情,其中任何非空字符串的行為都類似於True
,而空字符串的行為類似於False
。 因此if 'yes':
總是執行。
下面是在退出窗口的消息框中提問的代碼,然后如果用戶按是則退出。
from tkinter import *
from tkinter import messagebox
root=Tk()
def clicked():
label1=Label(root,text="This is text")
label1.pack()
def popup():
response=messagebox.askquestion("Title of message box ","Exit Programe ?",
icon='warning')
print(response)
if response == "yes":
b2=Button(root,text="click here to exit",command=root.quit)
b2.pack()
else:
b2=Button(root,text="Thank you for selecting no for exit .")
b2.pack()
button=Button(root,text="Button click",command=clicked)
button2=Button(root,text="Exit Programe ?",command=popup)
button.pack()
button2.pack()
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.