AttributeError: class Tk has no attribute 'tk' - python

hey guys i stuck on simple python GUI program
import Tkinter as tk
window = tk.Tk
text_box = tk.Entry(window)
def save_text():
str1 = text_box.get()
fx = open("file1.txt", "w")
fx.write(str1)
fx.close()
btn1 = tk.Button(window, text="Save", command="save_text")
text_box.pack()
btn1.pack()
window.mainloop()
i this error:
Traceback (most recent call last):
File "C:/Users/Saket/PycharmProjects/guiform1/firstform.py", line 5, in <module>
text_box = tk.Entry(window)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2385, in __init__
Widget.__init__(self, master, 'entry', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1965, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1943, in _setup
self.tk = master.tk
AttributeError: class Tk has no attribute 'tk'
Anybody having idea what am i doing wrong please help me??

You have to call tk.Tk to create an instance:
window = tk.Tk()
^^
You will then have a tk.Tk-type object to interact with.

Related

self.tk.call( _tkinter.TclError: image "pyimage3" doesn't exist

r_login = Tk()
r_login.title("Admin Login - Student Management System")
r_login.geometry("1280x720")
bg2 = PhotoImage(file="002.png")
lbl_bg2 = Label(r_login, image=bg2)
lbl_bg2.pack()
icon = PhotoImage(file='logo.png')
r_login.iconphoto(True, icon)
root = Tk()
root.title("Student Management System")
root.geometry("1280x720")
bg1 = PhotoImage(file="003.png")
lbl_bg1 = Label(root, image=bg1)
lbl_bg1.pack()
icon = PhotoImage(file='logo.png')
root.iconphoto(True, icon)
title = Label(root, text="Student Management System",
font=("Arial", 48, "bold"),
fg="black", bg="white")
title.place(x=226, y=30)
Output:
Traceback (most recent call last):
File "D:\Students Management\main.py", line 137, in <module>
lbl_bg1 = Label(root, image=bg1)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\amicr\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 3214, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\amicr\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 2628, in __init__
self.tk.call(
_tkinter.TclError: image "pyimage3" doesn't exist
I'm not being able to display the image in next. The first one is for admin for login and where the second is for another
Both of this image in my working directory and logo also. But some how I'm getting this error
You have more than one instance of Tk. All of the images are being created in the first instance and cannot be used in the second or subsequent instances.
You should not be creating two instances of Tk. Instead, if you need multiple windows. The second and subsequent windows should be instances of Toplevel.
For more info for why multiple instances of Tk is discouraged, read this

Label error in tkinter while exiting window

I am trying to make a digital clock through python tkinter .My code is
import tkinter,time
def exiter():
root.destroy()
root=tkinter.Tk()
root.title("Digital Clock")
root.geometry("340x100")
root.resizable(False,False)
root.protocol("WM_DELETE_WINDOW",exiter)
def time_setter():
hr=tkinter.Label(root,font=('k',60,'bold'),text=time.strftime("%H:%M:%S"))
hr.grid(row=0,column=0)
while True:
root.update()
time_setter()
After I close the window I get an error
Traceback (most recent call last):
File "c:\Users\Tanmay Daga\OneDrive\Documents\Programming\Clock-Tkinter\digital_clock.py", line 20, in <module>
time_setter()
File "c:\Users\Tanmay Daga\OneDrive\Documents\Programming\Clock-Tkinter\digital_clock.py", line 13, in time_setter
hr=tkinter.Label(root,font=('k',60,'bold'),text=time.strftime("%H:%M:%S"))
File "C:\Program Files\Python39-32\lib\tkinter\__init__.py", line 3145, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Program Files\Python39-32\lib\tkinter\__init__.py", line 2569, in __init__
self.tk.call(
_tkinter.TclError: can't invoke "label" command: application has been destroyed
How do I break the loop when the window is closed.
How do I know when the window is closed
from tkinter import *
from time import strftime
def clock_tick():
string = strftime('%H:%M:%S %p')
lbl.config(text=string)#set the text
lbl.after(1000, time)#updater
root=Tk()
lbl = Label(root, font=('calibri', 40, 'bold'),
background='purple',
foreground='white')
lbl.pack(anchor = 'center')
clock_tick()
root.title("Digital Clock")
root.geometry("340x100")
root.resizable(False,False)
root.mainloop() #this is the loop you are looking for instead of the while loop
The loop is wrong. For tkinter there is a built in loop that is much better to use. Exiting this with the X will provide a clean exit if you set the loop up by using root.mainloop(). Here is a good example of what you are trying to do
https://www.geeksforgeeks.org/python-create-a-digital-clock-using-tkinter/

I am just trying to show an image in a GUI. What am I doing wrong?

I am trying to display an image in a GUI, and don't understand what is wrong. I keep getting this error:
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
What should my code (especially the line with my_img=...) look like?
My Code:
from tkinter import *
from PIL import ImageTk,Image
my_img = ImageTk.PhotoImage(Image.open("iu.jpeg"))
my_label = Label(image=my_img)
my_label.pack()
root = Tk()
root.title("ICON PRACTICE")
root.iconbitmap('iu.ico')
button_quit = Button(root, text = "EXIT", command=root.quit)
button_quit.pack()
root.mainloop()
The full error
Traceback (most recent call last):
File "main.py", line 4, in <module>
my_img = ImageTk.PhotoImage(Image.open("test.png"))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageTk.py", line 112, in __init__
self.__photo = tkinter.PhotoImage(**kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 4064, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 3997, in __init__
raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image
Exception ignored in: <function PhotoImage.__del__ at 0x7f7148fadc10>
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Try doing this, its probably because you create the root object after opening the image and creating the photo object.
import os
from tkinter import *
from PIL import ImageTk,Image
root= Tk()
i = Image.open("C:/path/to/the/image/directory/image.png")
photo = ImageTk.PhotoImage(i)
root.mainloop()
The Label widget will only work after root = Tk() (Tk() starts the underlying Tcl interpreter) is declared. Then, all child widgets must have root as their first parameter (e.g., Label(root, text='hi')). You started the interpreter after you tried to use it, so Python raised an exception.

AttributeError: Menu instance has no attribute '__len__'

I am not familiar with the ways of python, i saw few other questions here with similar description, but could not fix this.
Error:
Traceback (most recent call last):
File "C:/Users/UT/PycharmProjects/tkinter/python_PET/main.py", line 16, in <module>
m = menu_bar_class(root)
File "C:/Users/UT/PycharmProjects/tkinter/python_PET/main.py", line 14, in __init__
self.master.config(self.menu)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1326, in configure
return self._configure('configure', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1312, in _configure
cnf = _cnfmerge(cnf)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 114, in _cnfmerge
for c in _flatten(cnfs):
AttributeError: Menu instance has no attribute '__len__'
Program:
from Tkinter import *
from tkFileDialog import *
import tkMessageBox
import ttk
root = Tk()
class menu_bar_class:
def __init__(self,master):
self.master = master
print("menu bar")
self.menu = Menu(self.master)
self.master.config(self.menu)
m = menu_bar_class(root)
root.mainloop()
You need to pass in the menu as a keyword argument:
self.master.config(menu=self.menu)
When you pass in a positional argument (so without the menu= part), then Tkinter expects to receive either a dictionary with configuration (so {'menu': self.menu}) or a sequence containing more sequences or dictionaries. Because self.menu is neither, you get the error you see.

AttributeError: object has no attribute 'tk'

I have searched quite a bit,but I couldn't find a solution to this. I'm trying to create a registration form using tkinter which later on i shall connect to a database. Here is the code :
from Tkinter import *
class MWindow(object):
def __init__(self,master):
self.frame=Frame(master)
self.frame.pack()
self.title= Label(self,text = "Login")
self.title.grid(row=0,column=1)
self.userid_label = Label(self,text ="Username: ")
self.userid_label.grid(row=1,column=0)
self.userid_entry= Entry(self)
self.userid_entry.grid(row=1,column=1)
self.password_label = Label(self,text ="Password: ")
self.password_label.grid(row=2,column=0)
self.password_entry= Entry(self)
self.password_entry.grid(row=2,column=1)
self.signin = Button (self,text = "Login",command=logging_in)
self.signin.grid(row=5,column=1)
self.signup = Button (self,text = "Sign Up",command=signing_up)
self.signin.grid(row=5,column=2)
def logging_in(self):
pass
def signing_up(self):
pass
root= Tk()
root.attributes('-fullscreen',True)
root.resizable(width=False, height=False)
root.title("My Registration Form")
app=MWindow(root)
root.mainloop()
Here is the error i get :
Traceback (most recent call last):
File "form.py", line 41, in
app=MWindow(root)
File "form.py", line 11, in init
self.title= Label(self,text = "Login")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2591, in init
Widget.init(self, master, 'label', cnf, kw)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2081, in init
BaseWidget._setup(self, master, cnf)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2059, in _setup
self.tk = master.tk
AttributeError: 'MWindow' object has no attribute 'tk'
I tried going to the library files to understand what's wrong,but being a beginner i can't make much of it. Some explanation of what's going wrong and why would be very helpful.
You're passing self in as the master / parent to your widgets.
e.g - Entry(self, ...) But, your class MWindow doesn't inherit from a Tkinter widget.
Perhaps you meant to use self.frame?
If you really want to use self you could do this:
import Tkinter as tk
...
class MWindow(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
abutton = tk.Button(self, ....)
If this is confusing, then here's a pretty good answer.
Since you mentioned the source code....
Look at the Tk() class. Which contains the following line:
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
Now, check out the BaseWidget class which all Widget's inherit from. This contains the following line:
self.tk = master.tk
You have you're base root window Tk() which has the attribute tk and every child of this set's an attribute tk to be the master's tk attribute. So on and so forth for nested widgets, since the parent of a widget could just be another widget it doesn't have to be the root window of course.

Categories

Resources