Tkinter askquestion dialog box

◇◆丶佛笑我妖孽 提交于 2019-12-09 16:20:04

问题


I have been trying to add an askquestion dialog box to a delete button in Tkinter. Curently I have a button that deletes the contents of a folder once it is pressed I would like to add a yes/no confirmation question.

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

Everytime I run this I get the "Deleted" statement even if I press "No". Can an if statement be added to a tkMessageBox?


回答1:


The problem is your if-statement. You need to get the result from the dialog (which will be 'yes' or 'no') and compare with that. Note the 2nd and 3rd line in the code below.

def deleteme():
    result = tkMessageBox.askquestion("Delete", "Are You Sure?", icon='warning')
    if result == 'yes':
        print "Deleted"
    else:
        print "I'm Not Deleted Yet"

Now for as to why your code seems to work: In Python a large number of types can be used in contexts where boolean values are expected. So for instance you can do:

arr = [10, 10]
if arr:
    print "arr is non-empty"
else:
    print "arr is empty"

The same thing happens for strings, where any non-empty string behaves like True and an empty string behaves like False. Hence if 'yes': always executing.



来源:https://stackoverflow.com/questions/11244753/tkinter-askquestion-dialog-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!