我需要用户在我的程序中输入一个整数。他们不应该能够输入字符串/浮点数。如果用户没有输入整数并单击按钮,我想要一个错误消息,如果您的用户名/密码在登录时不正确,则弹出类似于您获得的错误消息。
from tkinter import *
class GUI:
def __init__(self, parent):
self.iv = IntVar()
self.sb = Spinbox(parent, from_=0, to=10, textvariable = self.iv)
self.sb.pack()
self.b1 = Button(parent, text="Confirm")
self.b1.pack()
root = Tk()
root.geometry("800x600")
GUI = GUI(root)
root.title("Example")
root.mainloop()
答案 0 :(得分:1)
spinbox支持输入验证,其方式与Entry小部件完全相同。您可以设置validatecommand
,只允许输入数字。
例如:
class GUI:
def __init__(self, parent):
...
# add validation to the spinbox
vcmd = (parent.register(self.validate_spinbox), '%P')
self.sb.configure(validate="key", validatecommand=vcmd)
def validate_spinbox(self, new_value):
# Returning True allows the edit to happen, False prevents it.
return new_value.isdigit()
有关输入验证的详细信息,请参阅Interactively validating Entry widget content in tkinter
答案 1 :(得分:0)
Here is the code corresponding to Splinxyy suggestion:
convert the spinbox content with int()
inside a try/except block
from tkinter import *
from tkinter.messagebox import showerror
class GUI:
def __init__(self, parent):
self.iv = IntVar()
self.sb = Spinbox(parent, from_=0, to=10, textvariable = self.iv)
self.sb.pack()
self.b1 = Button(parent, text="Confirm", command=self.validate)
self.b1.pack()
def validate(self):
nb = self.sb.get()
try:
nb = int(nb)
# do something with the number
print(nb)
except Exception:
showerror('Error', 'Invalid content')
root = Tk()
root.geometry("800x600")
GUI = GUI(root)
root.title("Example")
root.mainloop()
答案 2 :(得分:0)
您可以使用状态=“只读”的选项。此选项也适用于Spinbox和Combobox。设置此选项后,用户只能从您提供的值中进行选择。