Tkinter询问对话框

11

我一直在尝试在Tkinter的删除按钮中添加一个askquestion对话框。目前我有一个按钮,当按下后会删除文件夹的内容,我想添加一个是/否确认问题。

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()

每次运行这个程序,即使我按下“否”,我都会得到“已删除”的提示。 是否可以向tkMessageBox添加if语句?

2个回答

27
问题出在你的if语句上。你需要从对话框中获取结果(将是'yes''no'),并进行比较。请注意以下代码中的第二和第三行。
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': 总是会被执行。


当你看到答案时,这显然很清晰。我尝试了各种'if == something'的组合,但没有想到使用tkMessageBox作为输入,我卡在了尝试使用askquestion的'yes'和'no'作为输入上。感谢您的帮助。 - Jeff
运行您的函数deleteme()也会创建一个空的tkinter框。有什么想法是什么原因导致这种情况? - Alex F

-1
以下是在退出窗口的消息框中询问问题并在用户按下“是”时退出的代码。
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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接