2017-06-15 48 views
0

我需要用户在我的程序中输入一个整数。他们不应该能够输入字符串/浮动。如果用户没有输入整数并点击按钮,我想要一个错误消息弹出类似于你登录到的东西时,如果你的用户名/密码不正确,你会得到一个。Tkinter如何防止用户输入字符串到旋转框中

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() 
+3

尝试文本/转换为整数除块尝试之内,那么它是否运行的,除了空的框 – Splinxyy

+0

莫非创建Spinbox时使用'values = range(11)'。 – SolarFactories

+0

@SolarFactories with python 3,你需要将'range'转换为'list':'values = list(range(11))'。 –

回答

0

这里是对应于Splinxyy建议的代码: /转换的纺纱器内容与int()一试内部除了块

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() 
1

的纺纱器支持输入验证以完全相同的方式与输入构件。您可以设置仅允许输入数字的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

相关问题