【问题标题】:Getting tkinter dialog to notify the user that their input is invalid让 tkinter 对话框通知用户他们的输入无效
【发布时间】:2018-02-07 07:13:46
【问题描述】:

我想知道如果用户的输入无效,您如何让 tkinter 通知用户。当他们输入负整数或非整数时,会弹出一个对话框并说他们的输入无效。然后它会让用户知道,然后它会让用户回到程序。我已经完成了第二部分,但是当我尝试执行无效的输入弹出窗口时出现了一些错误。它还弹出两个窗口,我不知道为什么。

有问题的代码:

import tkinter
from tkinter import *
import tkinter as tk





class TimeConverterUI():


    def __init__(self):


        #main functions
        self.root_window = Tk()
        self.root_window.geometry('400x150')
        self.root_window.title('Seconds Converter')
        self.text()
        self.quitValue=tk.Toplevel()
        self.invalidinputDialog=tk.Toplevel()
        self.calculate_button()
        self.quit_button()
        self.root_window.wait_window()


    def text(self):

        #label for seconds text along with the grid for it
        row_label = tkinter.Label(
              master = self.root_window, text = 'Seconds: ')

        row_label.grid( row = 0, 
                           sticky = tkinter.W)

        self.secondsEntry = Entry(master = self.root_window)
        self.secondsEntry.grid(row = 0, column = 1)

        #label for converted time along with the grid
        convert_label = tkinter.Label(
              master = self.root_window, text = 'Converted Time(H:M:S): ')

        convert_label.grid(row=1)

        self.result = Entry(master= self.root_window)
        self.result.grid(row = 1, column = 1)

    def calculate_button(self):

        #calculate button along with the placement
        quit = Button(self.root_window, text = "Calculate", command = self.calculate)
        quit.grid(row = 3, column = 0, columnspan = 3, pady=20,
                  sticky = tkinter.W)

    def calculate(self):

        try:

            #divides the seconds into minutes
            m,s = divmod(int(self.secondsEntry.get()),60)

            #divides the minutes into hours and returns h:m:s format
            h,m = divmod(m,60)

            c= ("%d:%02d:%02d" % (h, m, s))

            #after displaying the result, if the user wants to calculate again, deletes
            #previous result and recalculates

            self.result.delete(0,END)

            self.result.insert(0,c)



        except ValueError:

            #if user enters an input that's not an integer, exception is placed
            #d= 'Invalid Input'


            self.invalidinputDialog()
    def invalidinputDialog(self):

        self.invalidValue = tk.Toplevel()
        messageLabel = tk.Label(master=self.invalidValue,
                                text="Invalid Input.").grid(row=0,column=0)
        invalidContinue = tk.Button(master=self.invalidValue, text='Close',
                                    command = self.invalidValue.destroy).grid(row=1,column=1)

        self.result.delete(0,END)
        self.result.insert(0,d)

    def quit_button(self):

        #button for grid
        quit = Button(self.root_window, text = "Quit", command = self.quitDialog)
        quit.grid(row = 3, column = 3, columnspan = 3, pady=20,
                  sticky = tkinter.E)

    def quitDialog(self):

        self.quitValue = tk.Toplevel()
        messageLabel = tk.Label(master=self.quitValue,
                                text="Are you sure you want to quit?").grid(row=0,column=0)
        #closes both the main window and the message window
        continueButton = tk.Button(master=self.quitValue,text='Continue',
                                command=self.root_window.destroy).grid(row=1,column=2)
        #lets the user go back to previous screen if they cancel
        cancelButton = tk.Button(master=self.quitValue,text='Cancel',
                                command=self.quitValue.destroy).grid(row=1,column=1)
    def quit(self) -> bool:

        #quits the program and shell is refreshed
        self.root_window.destroy()
        return True





if __name__ == '__main__':

    convert=TimeConverterUI()

这就是问题所在。

def calculate(self):

    try:

        #divides the seconds into minutes
        m,s = divmod(int(self.secondsEntry.get()),60)

        #divides the minutes into hours and returns h:m:s format
        h,m = divmod(m,60)

        c= ("%d:%02d:%02d" % (h, m, s))

        #after displaying the result, if the user wants to calculate again, deletes
        #previous result and recalculates

        self.result.delete(0,END)

        self.result.insert(0,c)



    except ValueError:

        #if user enters an input that's not an integer, exception is placed
        #d= 'Invalid Input'


        self.invalidinputDialog()
def invalidinputDialog(self):

    self.invalidValue = tk.Toplevel()
    messageLabel = tk.Label(master=self.invalidValue,
                            text="Invalid Input.").grid(row=0,column=0)
    invalidContinue = tk.Button(master=self.invalidValue, text='Close',
                                command = self.invalidValue.destroy).grid(row=1,column=1)

    self.result.delete(0,END)
    self.result.insert(0,d)

【问题讨论】:

  • 你可以使用消息框或客户顶级消息框

标签: python tkinter dialog


【解决方案1】:

如果您只想告诉用户输入无效,您可以这样做

from tkinter import messagebox

messagebox.showinfo("Title", "Input invalid.")

Messagebox 确实需要从 tkinter 主库中单独导入。

话虽如此,您只需要导入一次 tkinter。您目前正在导入 tkinter 3 次:

import tkinter
from tkinter import *
import tkinter as tk

你应该使用:

import tkinter as tk

您可以将它用于大多数 tkinter 方法。您只需在小部件上使用前缀 tk.

示例tk.Entry()tk.Label()tk.Text() 等等。

至于您正在打开的额外空白窗口,它们来自您班级的__init__

class TimeConverterUI():


    def __init__(self):

        self.quitValue=tk.Toplevel() # causing an empty toplevel window to open in init
        self.invalidinputDialog=tk.Toplevel() # causing an empty toplevel window to open in init

您无需提前设置顶层。您可以在需要时简单地在方法中创建它。

【讨论】:

  • 哦,成功了!当我运行没有任何内容的代码时,还有一个额外的窗口。会不会来自 self.quitValue=tk.Toplevel()?
  • 如果您得到一个意外的窗口,那么它很可能来自Tk() 的额外实例或Toplevel() 的错误使用
  • @Accelerate 查看您的代码,问题来自 TimeCoinverterUI 类中的 __init__ 部分。您无需在此处定义顶层窗口。这就是打开空白窗口的原因。
  • 事实上你根本不需要在你的程序中使用toplevel。一切都可以用不同类型的消息框和 if 语句来完成。因此,您很可能需要删除 toplevel 的任何实例并将其替换为 messagebox.askquestionmessagebox.showinfo
  • 是的,我删除了代码的顶层部分,代码运行完美!谢谢
猜你喜欢
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多