我一直在尝试向 Tkinter 中的删除按钮添加一个提问对话框。目前我有一个按钮,一旦按下它就会删除文件夹的内容我想添加一个是/否确认问题。
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 中,可以在需要 bool 值的上下文中使用大量类型。所以例如你可以这样做:
arr = [10, 10]
if arr:
print "arr is non-empty"
else:
print "arr is empty"
同样的事情也发生在字符串上,其中任何非空字符串的行为都像 True
,而空字符串的行为像 False
。因此 if 'yes':
始终执行。
关于python - Tkinter 问问题对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11244753/