Skip to main content
 首页 » 编程设计

python之获取 tkinter 对话框以通知用户他们的输入无效

2025年02月15日10insus

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

有问题的代码:

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) 

请您参考如下方法:

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

from tkinter import messagebox 
 
messagebox.showinfo("Title", "Input invalid.") 

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

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

import tkinter 
from tkinter import * 
import tkinter as tk 

你应该使用:

import tkinter as tk 

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

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

至于打开的额外空白窗口,它们来自您类(class)的 __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 

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