首页 > 解决方案 > 让用户再次尝试输入正确的输入而不退出

问题描述

我正在尝试从 inputtxt (这是文本小部件)中获取一个数字,我需要测试输入;如果它不是一个数字,程序应该给用户另一个机会输入正确的输入。我这样做了;问题是警告消息显示,但程序继续。我需要一种在不退出程序的情况下给用户另一个机会的方法。

import tkinter
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image  
from tkinter import messagebox
import subprocess
from tkinter import filedialog
window = Tk()
window.title("Test")
window.geometry('650x400')
frame = Frame(window)
# Gets both half the screen width/height and window width/height
positionRight = 350
positionDown = 100
# Positions the window in the center of the page.
window.geometry("+{}+{}".format(positionRight, positionDown))
inputtxt2 = Text(window, height = 1, width =24,bg = "light yellow")
inputtxt2.pack()
inputtxt2.place(x=325, y=108)
def run_button():
    num_of_compare_points= inputtxt2.get('1.0', 'end-1c').strip().replace("\n","")
    if not (num_of_compare_points.isnumeric()):
        messagebox.showwarning("Warning","Please Enter a Valid Integer Value for Group Size!")
    print (int(num_of_compare_points)+1)
runButton = tkinter.Button(window, text ="Run",font = "Times", command = run_button)
runButton.pack()
runButton.place(x=260, y=320)
window.mainloop()

标签: pythontkinter

解决方案


目前还不清楚你的问题是什么。如果数据无效,您可以直接从函数返回而无需执行任何操作。

def run_button():
    num_of_compare_points= inputtxt2.get('1.0', 'end-1c').strip().replace("\n","")
    if not (num_of_compare_points.isnumeric()):
        messagebox.showwarning("Warning","Please Enter a Valid Integer Value for Group Size!")
        return
    print (int(num_of_compare_points)+1)

推荐阅读