【问题标题】:tKinter dialog button not respondingtKinter 对话框按钮没有响应
【发布时间】:2015-09-26 04:44:23
【问题描述】:

我是 tKinter 的新手。我尝试了这段代码,但它没有用。当我单击任何按钮(是/否)时,对话框不会关闭并且打印语句不会 打印。我知道在 Swing 中我需要事件来打印此语句。在 tKinter 中也一样吗?

from tkinter import *
import tkinter.messagebox

root = Tk()

answer=tkinter.messagebox.askquestion('Question','what is your name?')
if answer=='Yes':
print('I am King')

root.mainloop()

我该如何纠正它?

【问题讨论】:

    标签: python user-interface tkinter dialog


    【解决方案1】:

    您必须在“if”语句下使用缩进。即:

        if answer.lower() == 'yes': # this proofs against mistakes with user capitalisation
            print ('I am the king')
    

    【讨论】:

      【解决方案2】:

      返回的值将是 'yes' (全小写) ,但您正试图对照 'Yes' 检查它,因此它不会打印。尝试对照 'yes' 检查它。

      另外,实际应用程序root 直到您单击x 按钮后才会关闭,因为您正在定义Tk() 应用程序并进入其主循环。如果您希望它关闭(并且程序以 print 语句结束),那么您不需要 root=Tk() 或 root.mainloop() 。

      例子-

      import tkinter.messagebox
      
      answer=tkinter.messagebox.askquestion('Question','what is your name?')
      if answer=='yes':
          print('I am King')
      

      请注意,这会将'I am King' 打印到控制台中。


      回答评论中的问题-

      有没有一种方法可以隐藏名为 tk 的对话框——它是背景中的第二个对话框?

      为此,您必须使用Tk() 创建应用程序,然后您可以在其上使用root.withdraw()。示例 -

      import tkinter.messagebox
      from tkinter import Tk
      
      root = Tk()
      root.withdraw()
      answer=tkinter.messagebox.askquestion('Question','what is your name?')
      if answer=='yes':
          print('I am King')
      

      【讨论】:

      • 有什么方法可以隐藏名为 tk 的对话框——即后台的第二个对话框?
      • @BattleDrum 我已经为此添加了解决方案,您现在可以查看。
      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      相关资源
      最近更新 更多