【问题标题】:Tkinter askquestion dialog boxTkinter 提问对话框
【发布时间】:2012-06-28 12:34:20
【问题描述】:

我一直在尝试向 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()

每次运行时,即使按“否”,我也会收到“已删除”语句。可以在 tkMessageBox 中添加 if 语句吗?

【问题讨论】:

    标签: python tkinter tkmessagebox


    【解决方案1】:

    问题是你的if-statement。您需要从对话框中获取结果(将是'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': 总是在执行。

    【讨论】:

    • 看到答案就明白了。我尝试了'if == something'的各种组合,但没有考虑使用 tkMessageBox 作为输入,我一直在尝试使用 askquestion 的'yes'和'no'作为输入。感谢您的帮助。
    • 运行你的函数 deleteme() 也会创建一个空白的 tkinter 框。知道是什么原因造成的吗?
    【解决方案2】:

    下面是在退出窗口的消息框中提问的代码,如果用户按是则退出。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多