[Tkinter] tkinter.TclError: expected integer but got " " - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [Tkinter] tkinter.TclError: expected integer but got " " (/thread-39357.html) |
tkinter.TclError: expected integer but got " " - TWB - Feb-04-2023 Hello all, I am trying to build a function that i can use to check a imput field that requires a integer to make sure a character hasn't been entered. Anything I try gives me a error "tkinter.TclError: expected integer but got " " It seems to catch the error before i can run any error checking I have attached a snippet of the code below that is executable Any help is always appreciated # Introduction to Python Programming from tkinter import * import shelve import tkinter as tk from tkinter import ttk class MyFrame (Frame): def __init__(self): Frame.__init__(self) self.master.geometry("600x600") self.master.title("Student Scores") self.grid() #Display menue here here self.student_score = IntVar() self.student_score.set("") #label to prompt for input of score self.prompt = Label(self, text = "Enter students score: ") self.prompt.grid(row = 3, column = 0, sticky="W") #enable text field for score input self.input = Entry(self,textvariable=self.student_score) self.input.grid(row = 3, column = 2) #submit button self.button_submit = Button(self, text = "Submit", command = self.enter_student_scores) self.button_submit.grid(row = 10, column = 0, pady=20) #function to see entered student names and scores def enter_student_scores(self): student_score = self.student_score.get() #print output print(" Student Score is ",student_score) # function for error checking def error_checking(self): score = self.student_score.get() try: x = int(score) print("int is entered") except ValueError: print("Not a proper integer! Try it again") asn_frame = MyFrame() asn_frame.mainloop() RE: Error checking for Integer Field - deanhystad - Feb-04-2023 Calling IntVar.get() converts the entry text to an int. You need to wrap that in try/except tk.TclError. This doesn't happen if you use a StringVar, but then your code has to do the str to int conversion. You can use validation to limit what the user can type in an entry. This example only allows input that could be part of a valid integer string. import tkinter as tk class IntEntry(tk.Entry): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.variable = tk.StringVar(self, "") self.config( textvariable=self.variable, validate="key", validatecommand=(self.register(self.validate), "%P"), ) def validate(self, text): """Return True if text could be part of an integer string""" try: int(text+'0') # '' and '-' need to return True, so convert to '0' and '-0' except ValueError: return False return True def get(self): return int(self.variable.get()) def set(self, value): self.variable.set(str(value)) class MyWindow(tk.Tk): def __init__(self): super().__init__() prompt = tk.Label(self, text="Enter students score: ") prompt.grid(row=0, column=0, sticky="W", padx=10) self.student_score = IntEntry(self, justify=tk.RIGHT) self.student_score.grid(row=0, column=1) button = tk.Button(self, text="Submit", command=self.enter_student_scores) button.grid(row=0, column=2, padx=10, pady=10) def enter_student_scores(self): print(" Student Score is ", self.student_score.get()) MyWindow().mainloop()This code does not ensure that the entry contains a valid integer strng. '' and '-' must be allowed or typing input would be difficult. To properly validate input, you must allow invalid input, but prevent accepting values until all input is valid. import tkinter as tk class IntEntry(tk.Entry): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.variable = tk.IntVar(self, "") self.configure(textvariable=self.variable) def valid(self): try: self.variable.get() except tk.TclError: return False return True def get(self): return self.variable.get() def set(self, value): self.variable.set(value) class MyWindow(tk.Tk): def __init__(self): super().__init__() prompt = tk.Label(self, text="Enter students score: ") prompt.grid(row=0, column=0, sticky="W", padx=10) self.student_score = IntEntry(self, justify=tk.RIGHT) self.student_score.grid(row=0, column=1) self.student_score.variable.trace("w", self.validate_form) self.accept = tk.Button( self, text="Submit", command=self.enter_student_scores, state=tk.DISABLED ) self.accept.grid(row=0, column=2, padx=10, pady=10) def validate_form(self, *_): self.accept["state"] = tk.ACTIVE if self.student_score.valid() else tk.DISABLED def enter_student_scores(self): print(" Student Score is ", self.student_score.get()) MyWindow().mainloop()The validation tools in tkinter are more tools for writing validation code than useful validation tools themselves. RE: Error checking for Integer Field - TWB - Feb-19-2023 Thank you I found that helpful and was able to resolve my issue |