This question already has answers here:
AttributeError: 'str' object has no attribute 'tk' in tkinter Label
(2 answers)
Closed 10 months ago.
Here is my code:
window = tk.Tk()
version = tk.Label(text="hi",
fg="orange",
bg="black",
width=20,
height=10,
)
version.pack()
enter = tk.Button(text="START",fg="blue",width=20,height=7)
enter.pack()
def click(event):
version.forget()
enter.forget()
name = tk.Label("name")
entry = tk.Entry()
name.pack()
entry.pack()
enter.bind("<Button-1>", click)
window.mainloop()
As you can see, I wanted to make a Label and an Entry appear once the START button is clicked.
When I click the button, though, it returns this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "/Users/name/Desktop/project/gui/main.py", line 19, in click
name = tk.Label("name")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 3148, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2566, in __init__
BaseWidget._setup(self, master, cnf)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2535, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
I don't know what is happening here.
Per the error statement, the origin of the problem is this line:
File "/Users/name/Desktop/project/gui/main.py", line 19, in click
name = tk.Label("name")
The first expected argument of a Label is the "master", or parent window.
Related
I decided to make a tkinter timer but am receiving a very strange error.
Here is the code and the error:
import tkinter as tk
import time
window = tk.Tk()
window.title("Hello wold")
window.geometry("300x300")
timer = int(input("time in seconds"))
for i in range(timer):
timer -= 1
print(timer)
time.sleep(1)
hello = tk.Label("timer")
hello.pack()
tk.mainloop()
The error:
Traceback (most recent call last):
File "main.py", line 14, in <module>
hello = tk.Label("timer")
File "/usr/lib/python3.8/tkinter/__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 2561, in __init__
BaseWidget._setup(self, master, cnf)
File "/usr/lib/python3.8/tkinter/__init__.py", line 2530, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
To change the text of a label you need to define the text property:
hello = tk.Label(text="timer")
This will set the text of the label to "timer", but if you want to set it as the variable you previously declared (called timer) - simply remove the quotation marks.
hello = tk.Label(text=timer)
This will set the text of the label to whatever the variable 'timer' is equal to.
However you also need to set the window, which leaves the final code to this:
hello = tk.Label(window, text=timer)
I added tk.StringVar in line 16.
I added textvariable=string_variable in line 17
tk.mainloop was relocated outside of the loop block in line 20
Here is code:
import tkinter as tk
import time
window = tk.Tk()
window.title("Hello wold")
window.geometry("300x300")
timer = int(input("time in seconds"))
for i in range(timer):
timer -= 1
print(timer)
time.sleep(1)
string_variable = tk.StringVar(window, timer)
hello = tk.Label(window, textvariable=string_variable)
hello.pack()
tk.mainloop()
Output result:
Im trying to make a tkinter window but this shows up for some reason, i really dont know what i did wrong
root.title('RNG')
root.geometry('300x300')
button = Button(root, text = 'talk', bd = '5',)
button.pack(side = 'top')
text = Text(master=BOTTOM)
text.pack(side=BOTTOM)
the error:
File "/home/valtok/PycharmProjects/tests/waifu simulator/RNG.py", line 65, in <module>
text = Text (master=BOTTOM)
File "/usr/lib/python3.8/tkinter/__init__.py", line 3554, in __init__
Widget.__init__(self, master, 'text', cnf, kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 2561, in __init__
BaseWidget._setup(self, master, cnf)
File "/usr/lib/python3.8/tkinter/__init__.py", line 2530, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
Instead of this:
text = Text(master=BOTTOM)
Write this:
text = Text(master=root)
This question already has answers here:
_tkinter.TclError: image "..." doesn't exist
(3 answers)
Closed 4 years ago.
Here is part of my code called within a function:
#Labels and Window layout
lsfpy = Tk()
lsfpy.title("Helicopters Sydney")
lsfpy.resizable(False, False)
Label(lsfpy, text="Locations in Sydney").grid(row=0)
Label(lsfpy, text="To").grid(column = 1, row=1, sticky=N)
Label(lsfpy, text="From").grid(column = 1, row=2, sticky = W)
Label(lsfpy, text="").grid(column = 1, row=3)
Label(lsfpy, text="Date").grid(column = 1, row=4, sticky=SW)
Label(lsfpy, text="Time").grid(column = 1, row=5, sticky=SW)
#Map
photo = PhotoImage(file = 'GUI Files/Map/Sydmap.gif')
photo = photo.subsample(2)
lbl = Label(lsfpy,image = photo)
lbl.grid(column=0, row=3)
When I run it, I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1702, in __call__
return self.func(*args)
File "/Users/62633/Documents/2018/SDD/Webdrone Sydney/Freight.py", line 22, in calculateandnext
saveandgotomapf(tp,am1,am2,am3,am4,am5)
File "/Users/62633/Documents/2018/SDD/Webdrone Sydney/Freight.py", line 55, in saveandgotomapf
locationfreight(fdpy)
File "/Users/62633/Documents/2018/SDD/Webdrone Sydney/Locationfreight.py", line 192, in locationfreight
lbl = Label(lsfpy,image = photo)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2763, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2296, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage4" doesn't exist
When I comment out
photo = photo.subsample(2)
The error slightly changes to:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1702, in __call__
return self.func(*args)
File "/Users/62633/Documents/2018/SDD/Webdrone Sydney/Freight.py", line 22, in calculateandnext
saveandgotomapf(tp,am1,am2,am3,am4,am5)
File "/Users/62633/Documents/2018/SDD/Webdrone Sydney/Freight.py", line 55, in saveandgotomapf
locationfreight(fdpy)
File "/Users/62633/Documents/2018/SDD/Webdrone Sydney/Locationfreight.py", line 192, in locationfreight
lbl = Label(lsfpy,image = photo)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2763, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2296, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage3" doesn't exist
If I copy the code snippet into a new file, there are no problems.
What is causing these errors?
In your recent edit, you mentioned the code was in a function, that made all the difference.
The PhotoImage is not kept by tkinter, so you must keep a reference to it before Python's garbage collector gobbles up the image after the function returns. When it does, tkinter couldn't find your image anymore, thus your error saying that the image doesn't exist.
As recommended if effbot, you can do:
photo = PhotoImage(file = 'GUI Files/Map/Sydmap.gif')
photo = photo.subsample(2)
lbl = Label(lsfpy,image = photo)
lbl.image = photo
lbl.grid(column=0, row=3)
You must keep a reference to the image object in your Python program,
either by storing it in a global variable, or by attaching it to
another object.
Note: When a PhotoImage object is garbage-collected by
Python (e.g. when you return from a function which stored an image in
a local variable), the image is cleared even if it’s being displayed
by a Tkinter widget. To avoid this, the program must keep an extra
reference to the image object. A simple way to do this is to assign
the image to a widget attribute, like this:
label = Label(image=photo)
label.image = photo # keep a reference! label.pack()
The following is a simple tkinter program that displays an empty window:
# firstTkinter2.py
from Tkinter import Tk, Label
top = Tk()
l = Label(top, "Hello World")
l.pack()
# Give the window a title.
top.title("My App")
# Change the minimum size.
top.minsize(400, 400)
# Change the background colour.
top.configure(bg = "green")
# Run the widget.
top.mainloop()
I run the above code but it encountered an error:
zhiwei#zhiwei-Lenovo-Rescuer-15ISK:~/Documents/python programs/tkinter$ python tk2.py
Traceback (most recent call last):
File "tk2.py", line 4, in <module>
l = Label(top, "Hello World")
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 2600, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 2094, in __init__
for k in cnf.keys():
AttributeError: 'str' object has no attribute 'keys'
How can I fix this error and let it run properly?
Try to replace:
l = Label(top, "Hello World")
on
l = Label(top, text="Hello World")
# ^^^^^^^
Use Label(top, text="Hello World")
You have to use the text argument.
I'm trying to add a ttk calendar into my Tkinter GUI. The problem is that it raises _tkinter.TclError: can't pack .34164128 inside .34161248.34161448.34161608
import Tkinter
import tkSimpleDialog
import ttkcalendar
class CalendarDialog(tkSimpleDialog.Dialog):
"""Dialog box that displays a calendar and returns the selected date"""
def body(self, master):
self.calendar = ttkcalendar.Calendar(master)
self.calendar.pack()
def apply(self):
self.result = self.calendar.selection
# Demo code:
def main():
root = Tkinter.Tk()
root.wm_title("CalendarDialog Demo")
def onclick():
print 'click'
cd = CalendarDialog(root)
button = Tkinter.Button(root, text="Click me to see a calendar!", command=onclick)
button.pack()
root.update()
root.mainloop()
if __name__ == "__main__":
main()
TRACEBACK:
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 32, in <module>
main()
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 23, in main
cd = CalendarDialog(root)
File "C:\Python27\lib\lib-tk\tkSimpleDialog.py", line 64, in __init__
self.initial_focus = self.body(body)
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 9, in body
self.calendar = ttkcalendar.Calendar(master)
File "C:\Users\Milano\PycharmProjects\MC\plots\ttkcalendar.py", line 52, in __init__
self.__place_widgets() # pack/grid used widgets
File "C:\Users\Milano\PycharmProjects\MC\plots\ttkcalendar.py", line 110, in __place_widgets
self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1940, in pack_configure
+ self._options(cnf, kw))
_tkinter.TclError: can't pack .34164128 inside .34161248.34161448.34161608
Do you know where is the problem?
The fault is that you don't have an __init__ method in the class CalendarDialog. So just rename the body method to __init__. Now you have initialized the instance every time one is made and a pack() method is defined.
I also encountered this problem putting a ttkCalendar into a Dialog box.
I suspect the author of this post "borrowed" the same code for building a calendar as I did:
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=2ahUKEwiWgYWKsJ3nAhVKl3IEHYrhCU8QFjABegQICBAB&url=https%3A%2F%2Fsvn.python.org%2Fprojects%2Fpython%2Ftrunk%2FDemo%2Ftkinter%2Fttk%2Fttkcalendar.py&usg=AOvVaw0ifTox4EI7CtBFWlRYD_m9
There are two problems I found using this code to create a Calendar object and placing it into a Dialog box.
The first one causes the traceback as shown in the post. The fix is to modify the ttkcalendar.py file to pack the calendar when it is created, not after it is created using the pack() function.
Here is the diff:
102c102
< self._calendar = ttk.Treeview(show='', selectmode='none', height=7)
---
> self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7)
109c109
< self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
---
> self._calendar.pack(expand=1, fill='both', side='bottom')
Once you make this change, the calendar will appear in the dialog box. However, your problems are not yet done. Another exception occurs when trying to set the minimum size of the calendar:
Exception in Tkinter callback
Traceback (most recent call last):
File "/home/richawil/Applications/anaconda3/envs/TLM/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/richawil/Documents/Programming/Apps/TLM/TLM/ttkcalendar.py", line 134, in __minsize
width, height = self._calendar.master.geometry().split('x')
AttributeError: 'Calendar' object has no attribute 'geometry'
I have not been able to fix this issue other than to comment out the call to self.__minsize.
63c62,63
< self._calendar.bind('<Map>', self.__minsize)
---
> # Commented out because _calendar object does not support geometry() function
> #self._calendar.bind('<Map>', self.__minsize)