Python Forum
[Tkinter] tkinter.TclError: expected integer but got " "
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] tkinter.TclError: expected integer but got " "
#1
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()
Reply
#2
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.
Reply
#3
Thank you I found that helpful and was able to resolve my issue
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tkinter.TclError: can't invoke "canvas" command cybertooth 8 5,772 Feb-23-2023, 06:58 PM
Last Post: deanhystad
  [Tkinter] _tkinter.TclError: can't invoke "destroy" command: application has been destroyed knoxvilles_joker 6 15,269 Apr-25-2021, 08:41 PM
Last Post: knoxvilles_joker
  "tkinter.TclError: NULL main window" Rama02 1 5,781 Feb-04-2021, 06:45 PM
Last Post: deanhystad
  [Tkinter] _tkinter.TclError: bitmap "Icon.gif" not defined djwilson0495 2 12,857 Aug-05-2020, 02:27 PM
Last Post: wuf
  [Tkinter] _tkinter.TclError: image "pyimage2" doesn't exist Killdoz 1 10,511 May-30-2020, 09:48 AM
Last Post: menator01
  Converting Entry field value to integer in tkinter scratchmyhead 2 4,880 May-11-2020, 03:41 PM
Last Post: scratchmyhead
  tkinter.TclError: bad window path name kenwatts275 3 14,628 Apr-26-2020, 08:16 PM
Last Post: kenwatts275

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020