(Python version: 3.1.1)
I am having a strange problem with StringVar in tkinter. While attempting to continuously keep a Message widget updated in a project, I kept getting an error while trying to create the variable. I jumped out to an interactive python shell to investigate and this is what I got:
>>> StringVar
<class 'tkinter.StringVar'>
>>> StringVar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\tkinter\__init__.py", line 243, in __init__
Variable.__init__(self, master, value, name)
File "C:\Python31\lib\tkinter\__init__.py", line 174, in __init__
self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
>>>
Any ideas? Every example I have seen on tkinter usage shows initializing the variable with nothing sent to the constructor so I am at a loss if I am missing something...
StringVar needs a master:
>>> StringVar(Tk())
<Tkinter.StringVar instance at 0x0000000004435208>
>>>
or more commonly:
>>> root = Tk()
>>> StringVar()
<Tkinter.StringVar instance at 0x0000000004435508>
When you instantiate Tk a new interpreter is created. Before that nothing works:
>>> from Tkinter import *
>>> StringVar()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python26\lib\lib-tk\Tkinter.py", line 251, in __init__
Variable.__init__(self, master, value, name)
File "C:\Python26\lib\lib-tk\Tkinter.py", line 182, in __init__
self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
>>> root = Tk()
>>> StringVar()
<Tkinter.StringVar instance at 0x00000000044C4408>
The problem with the examples you found is that probably in the literature they show only partial snippets that are supposed to be inside a class or in a longer program so that imports and other code are not explicitly indicated.
Related
An error occurred by pystary
My coding enviroment:windows10, python3.7
I want to make a tray application.But an error occurred.
Here is my code:
from pystray import MenuItem as item
import pystray
from PIL import Image
def show():
print(":D")
image = Image.open("TrayIcon.jpg")
menu = (item('print(":D")', show))
icon = pystray.Icon("name", image, "title", menu)
icon.run()
Here is the error:
Traceback (most recent call last):
File "C:/Users/admin/AppData/Roaming/JetBrains/PyCharmCE2022.1/scratches/scratch.py", line 12, in <module>
icon = pystray.Icon("name", image, "title", menu)
File "D:\py3.7\lib\site-packages\pystray\_win32.py", line 32, in __init__
super(Icon, self).__init__(*args, **kwargs)
File "D:\py3.7\lib\site-packages\pystray\_base.py", line 89, in __init__
else Menu(*menu) if menu is not None \
TypeError: type object argument after * must be an iterable, not MenuItem
Exception ignored in: <function Icon.__del__ at 0x000001CC7BE15EA0>
Traceback (most recent call last):
File "D:\py3.7\lib\site-packages\pystray\_win32.py", line 50, in __del__
if self._running:
AttributeError: 'Icon' object has no attribute '_running'
menu must be an iterable (a list or a tuple) but currently it is just a single item. You need to add a comma to make it a tuple:
menu = (item('print(":D")', show),)
In python, (42) is just the number 42, but (42,) is a tuple -- an iterable object -- containing the number 42.
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.
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.
This question already has answers here:
Issue with 'StringVar' in Python Program
(2 answers)
Closed 7 years ago.
I have python 2.7.2-4 (Archlinux), and from
import Tkinter
Tkinter.StringVar()
results
Traceback (most recent call last):
File "/tmp/foo.py", line 3, in <module>
foo = Tkinter.StringVar()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 251, in __init__
Variable.__init__(self, master, value, name)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 182, in __init__
self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
Exception AttributeError: "StringVar instance has no attribute '_tk'" in <bound method StringVar.__del__ of <Tkinter.StringVar instance at 0x1815710>> ignored
Call tk.Tk() before tk.StringVar():
import Tkinter as tk
root=tk.Tk()
tk.StringVar()
from tkinter import *
app=Tk()
app.title(" BRAIN SYNCRONIZATION SOFTWARE ")
e1=Entry(app).pack()
t1=Text(app).pack()
def InputFun():
file=open("acad.txt","a")
file.write("%s;%s"%(t1.get("0.1",END),e1.get()))
file.close()
b1=Button(app,text="INPUT",command=InputFun,height=3,width=4).pack(side=LEFT,padx=30,pady=30)
This is the code I wrote, but I am repeatedly getting the following error when I press the input button:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
File "C:\Users\vonn\Desktop\brain syncronization.py", line 15, in InputFun
file.write("%s"%t1.get("0.1",END))
AttributeError: 'NoneType' object has no attribute 'get'
Why is it not writing the file?
t1=Text(app).pack()
should be
t1=Text(app)
t1.pack()
The Tkinkter pack() method returns None, you can't run .get() on it, but need to keep t1 referring to the text object itself.
I don't think that Entry(app).pack() will return anything. Do you mean e1=Entry(app); e1.pack()?