0
votes

I'm having 'fun' with Python TkInter. Unfortunately, my code returns an error

AttributeError: 'str' object has no attribute 'bind'

I've already assigned StringVar type to my variable, but it doesn't seem to work.

This is my code:

import tkinter
from tkinter import StringVar
from typing import Type

window = tkinter.Tk()

label = tkinter.Label(
    text='Hello TkInter',
    foreground='white',
    background='black',
)
entry = tkinter.Entry(
    foreground='yellow',
    background='blue',
    width=50,
)


UserEntry: Type[StringVar] = entry.get()


def PrintUserEntry():
    print(UserEntry.widget.get())


label.pack()
entry.pack()
UserEntry.bind('<Enter>', PrintUserEntry())
window.mainloop()

Any ideas?

1
You defined UserEntry as the result of entry.get() therefore it will be a string not a tkinter widget. Change UserEntry.bind('<Enter>', PrintUserEntry()) to entry.bind('<Enter>', PrintUserEntry)TheLizzard
Btw you know that the event <Enter> is for when the user's mouse hovers over the widget. I think you wanted to use <Return> which is the enter key on the keyboard.TheLizzard
Also just noticed it but you need to change def PrintUserEntry() to def PrintUserEntry(event) because when you bind an event is passed in the function.TheLizzard
Now it returns 2 errors. Code launches and I can enter text, but when i press enter this comes up: line 1884, in __call__ return self.func(*args) and line 22, in PrintUserEntry print (UserEntry.widget.get()) AttributeError: 'str' object has no attribute 'widget'Krzysztoff
That is because UserEntry is still a string not a StringVar. Look at my answer bellow.TheLizzard

1 Answers

1
votes

The full working code:

import tkinter
from tkinter import StringVar
from typing import Type

window = tkinter.Tk()

label = tkinter.Label(
    text='Hello TkInter',
    foreground='white',
    background='black',
)
entry = tkinter.Entry(
    foreground='yellow',
    background='blue',
    width=50,
)


UserEntry: Type[str] = entry.get()


def PrintUserEntry(event):
    print(entry.get())


label.pack()
entry.pack()
entry.bind('<Return>', PrintUserEntry)
window.mainloop()

First of all when you wrote UserEntry.bind('<Enter>', PrintUserEntry()), you didn't want to automatically call the function so you where actually trying to do this: UserEntry.bind('<Enter>', PrintUserEntry).

Second of all when you defined UserEntry it was actually a str not a StringVar so both UserEntry.widget.get() and UserEntry.bind(...) would fail.

Also you need to change def PrintUserEntry() to def PrintUserEntry(event) because when you bind, an event is passed in the function.

Lastly, when bind to <Enter> it is actually for when the user's mouse hovers over the widget. I think you wanted to use <Return> which is the enter key on the keyboard.