Getting a strange _tkinter.TclError: unknown option - python

I have made a small game where you progress through your life much like instlife but made in python with Tkinter. It is not complete and no where near being completed as i always get this same error.
This is my code
import tkinter
window = tkinter.Tk()
window.geometry("275x400")
window.title("Life")
year = 1980
age = 0
def ageButton():
global year
global age
year += 1
age += 1
yearText.configure(text=year)
dynamicText.configure("You are %d" %age)
yearText = tkinter.Label(window, text=year, anchor="n", width="270")
dynamicText = tkinter.Label(window, text="You are %d" %age, anchor="n",
width="270", height="495")
ageButton = tkinter.Button(window, text="Age", width="270",
command=ageButton)
ageButton.pack()
yearText.pack()
dynamicText.pack()
window.mainloop()
this is the error i get
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\Ed\Desktop\Lifee2\Life2.py", line 16, in ageButton
dynamicText.configure("You are %d" %age)
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1482, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1472, in _configure
return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1460, in _getconfigure1
x = self.tk.splitlist(self.tk.call(*args))
_tkinter.TclError: unknown option "-You are 1"

When you call the configure method, you must tell tkinter what value you are changing. In your case you need to change this:
dynamicText.configure("You are %d" %age)
... to this:
dynamicText.configure(text="You are %d" %age)

Related

No idea what's causing this error "AttributeError: '_io.TextIOWrapper' object has no attribute 'tk'"

The code keeps throwing the AttributeError: '_io.TextIOWrapper' object has no attribute 'tk' and I can't figure out what's causing it, I looked at other posts and nothing has helped me to get an idea of what's going on.
Below is the code that's causing it.
def showhwk(lesson, popup):
lesson = lesson.replace("/","")
popup.withdraw()
show = Tk()
show.title("Homework marks for "+lesson)
show.geometry("+{}+{}".format(positionRight, positionDown))
try:
with open(lesson+".csv", "r") as show:
csvlist = list(csv.reader(show))
for label in range (len(csvlist)):
Label(show, text = "hello").grid(row = label)
except FileNotFoundError:
show.title("Error!")
error = Label(show, text = "Homework file was not found")
error.grid(row = 0)
def goback3(show):
popup.deiconify()
show.withdraw()
returnbut = Button(show, text = "Return", bg = "#79838e", command = lambda: goback3(show)).grid(row = 40, sticky = W+E)
This is the full error:
Traceback (most recent call last):
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 242, in <lambda>
show = Button(popup, text = "Show homework marks", bg = "green", command = lambda: showhwk(lesson, popup))
File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 278, in showhwk
Label(show, text = "hello").grid(row = label)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2561, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2530, in _setup
self.tk = master.tk
AttributeError: '_io.TextIOWrapper' object has no attribute 'tk'
You first define show like this:
show = Tk()
Later, you redefine show to be an open file handle with this statement:
with open(lesson+".csv", "r") as show:
Then, you try to use show as the master for a widget here:
Label(show, text = "hello").grid(row = label)
Because show is no longer a widget, it can't be used as the master for another widget. And that is why you get a tkinter error.

AttributeError when trying to change tkinter label color with bound command

I am trying to create a tkinter label that changes color when clicked to show that it has been visited. I keep getting an attribute error saying that Show_Label has no attribute 'fg'. Please help! Here is the code being used.
class Sheet_Label(Label):
def __init__(self,master,text):
Label.__init__(self,master,text=text,cursor="hand2",font="Times 16 underline",fg="blue")
def button_click(event):
if self.fg =="blue":
self.fg = "purple"
else:
self.fg = "purple"
location = os.getcwd()
file = webbrowser.open_new(location + '\\' + "hello.txt")
self.bind("<Button-1>",func=button_click)
def sheets_view():
sheets_window = Toplevel(window)
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
hello.pack(padx=10,pady=10)
sheets_window.title("Production Sheets")
sheets_window.focus()
x = (screen_width/2) - (500/2)
y = (screen_height/2) - (500/2)
sheets_window.geometry("%dx%d+%d+%d" % (500,500,x,y))
sheets_window.resizable(0,0)
Here is the error message:
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "inventory.py", line 311, in sheets_view
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 24, in __init__
self.action = action
NameError: name 'action' is not defined
PS C:\Users\napaf\Documents\Programming\adco_project> python inventory.pyException in Tkinter callback
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 27, in button_click
if self.fg =="blue":
AttributeError: 'Sheet_Label' object has no attribute 'fg'
You aren't initializing self.fg until button_click has been called, but at that point it's too late because you're trying to reference self.fg before setting it.
Also, self.fg is not the same as the fg attribute when you create the widget (eg: Label(..., fg="blue"). If you want to get the value of the widget attribute you should use self.cget('fg') or use the shortcut self['fg']. If you want to set it from within the class itself you should use self.configure(fg="purple").

'File not found' while importing gif for Tkinter.Label

I'm trying to import gif into a Tkinter.Label. I'm getting a file does not exist error. I have double checked the path and file name.
Below is the error message I get.
Traceback (most recent call last):
File "C:\Users\sachin\Desktop\Project California.py", line 39, in <module>
if __name__=='__main__': main()
File "C:\Users\sachin\Desktop\Project California.py", line 35, in main
feedback = Feedback(root)
File "C:\Users\sachin\Desktop\Project California.py", line 11, in __init__
self.logo = PhotoImage(file= "‪C:\\Users\\sachin\\Desktop\\signature.gif")
File "C:\Users\sachin\AppData\Local\Programs\Python\Python36
\lib\tkinter\__init__.py", line 3542, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "‪C:\Users\sachin\Desktop\signature.gif": no
such file or directory
Here is the code I used.
def __init__(self,master):
self.frame_header = ttk.Frame(master)
self.logo = PhotoImage(file= "‪C:\\Users\\sachin\\Desktop\\signature.gif")
ttk.Label(self.frame_header, image = self.logo)
I'm a noob in python programming. Apologies if the questions is too trivial.
I get the same error and I'm sure the path is right as well. In fact, it seems to find the file every other time it tries, with very similar code.
for r in range(0,5):
for c in range(1,4):
fn = file_name(c)
try:
photo = tk.PhotoImage(fn)
tk.Button(C, image = photo, width = "16", height = "16").grid(row = r,column = c)
except Exception as exception:

Updating Python tkinter label in realtime

I want to update my label in python after the loop has started.
Sadly I get the error
File "mygui.py", line 19, in <module>
GUI.user_said("General Kenobi")
File "mygui.py", line 16, in user_said
self.my_label['text'] = self.label_text
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1486, in __setitem__
self.configure({key: value})
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1479, in configure
return self._configure('configure', cnf, kw)
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1470, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!label"
which doesn't help me at all...
My Code:
from tkinter import *
class MyGUI:
"""A simple class"""
def __init__(self):
self.__main_window = Tk()
self.label_text = "Hello There"
self.my_label = Label(self.__main_window, text=self.label_text)
self.my_label.pack()
self.__main_window.mainloop()
def user_said(self, users_request):
"""Returns what the user says"""
self.label_text = "You said:\n{}\n\n".format(users_request)
self.my_label.config(text=self.label_text)
GUI = MyGUI()
GUI.user_said("General Kenobi")
I'm very glad if someone helps me to find a solution for my problem.
Because MyGUI.__init__ calls self.__main_window.mainloop(), it will not return until the main window is destroyed. Therefore, by the time you call GUI.user_said("General Kenobi"), none of the widgets exist any more.

Creating multiple variables / strings within loops in Python

I'm trying to create a program that, well, looks something like this:
self.b1 = Checkbutton(self, variable=self.b1v, text="1.")
self.b1.grid()
self.b2v = IntVar()
self.b2 = Checkbutton(self, variable=self.b2v, text="2.")
self.b2.grid()
self.b3v = IntVar()
self.b3 = Checkbutton(self, variable=self.b3v, text="3.")
self.b3.grid()
self.b4v = IntVar()
Well, kinda like that, just... 30+ times. There has GOT to be a better way to do this. However, I have no idea how to do this in a loop. I imagine it would look something like this:
while i <= 32:
n = "self.b" + str(i) + "v = IntVar() \n"
n += "self.b" + str(i) + " = Checkbutton(self, variable=self.b" + str(i) + "v) \n"
n += "self.b" + str(i) + ".grid()\n"
exec(n)
...Or something like that... But that throws an error:
Traceback (most recent call last):
File "/Users/jonahswersey/Documents/toggle flags.py", line 126, in <module>
app = Application()
File "/Users/jonahswersey/Documents/toggle flags.py", line 93, in __init__
self.createWidgets()
File "/Users/jonahswersey/Documents/toggle flags.py", line 117, in createWidgets
exec(m)
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 2337, in __init__
Widget.__init__(self, master, 'checkbutton', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1923, in __init__
BaseWidget._setup(self, master, cnf)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1903, in _setup
if cnf.has_key('name'):
AttributeError: IntVar instance has no attribute 'has_key'
...whereas just manually entering them doesn't. Anyone have any advice for me?
Something like this?
num_buttons = 3
self.b_vars = [IntVar() for i in range(num_buttons)]
self.b = [CheckButton(self, variable=self.b_vars[i], text="%d." % (i + 1)) for i in range(num_buttons)]
for button in self.b:
button.grid()
You're looking for setattr().

Categories

Resources