Skip to content Skip to sidebar Skip to footer

Tkinter: Attributeerror Using .get()

I am trying to retrieve a variable from a Tkinter Wiget but I am running into this error message: AttributeError: 'int' object has no attribute 'get' Here is the widget code JobNE

Solution 1:

The get() method is part of several widgets in tkinter and is not something that you can use on a normal int or str object. get() must be called on a variable that is a widget object that has a get() method, like Entry.

Its likely you need to do:

JobNEntry.get()

This will get the current value from the entry field as a string.

If you want to save the value of that string you can. There are several tutorials on Stack Overflow and the web that go into detail on how to save a string to a file.

Looking at the code you have shown us, it's possible you have not created your IntVar() correctly.

Make sure you define the IntVar() first then set that variable as the textvariable.

Something like this:

JobNo = tk.IntVar()
JobNEntry = tkinter.Entry(menu, textvariable = JobNo)

Solution 2:

The attribute error might be because you havnt already initialized the variable JobNo as an 'IntVar'

This is the code i have come up with :

import tkinter as tkinter

menu=tkinter.Tk()
JobNo=tkinter.IntVar()
JobNEntry = tkinter.Entry(menu, textvariable = JobNo)
JobNEntry.grid(row=2, column=2, sticky="W")
JobNo=JobNo.get()
menu.mainloop()

You need to initialize JobNo as an Integer Variable using IntVar()

JobNo=tkinter.IntVar()

And then use it in the Entrybox. If you had some string to add to the entry, you should initialise as StringVar() Also when you initialize, make sure you do it after opening the Tk window.(here i put it after menu=tkinter.Tk())

Solution 3:

Something like this:

from tkinter import *
from tkinter import ttk

def save_job_no():
    try:
        n = job_no.get()
    except TclError:
        status.config(text = "This is not an integer")
        return False
    status.config(text="")
    f = open("my_file.txt", "w")
    f.write(str(n))
    return True

root = Tk()

job_no = IntVar()
entry = ttk.Entry(root, width = 30, textvariable = job_no)
entry.grid()
label = ttk.Label(root, textvariable = job_no)
label.grid()
status = ttk.Label(root)
status.grid()
button = ttk.Button(root, text = "Write to a file", command = save_job_no)
button.grid()

root.mainloop()

Post a Comment for "Tkinter: Attributeerror Using .get()"