Updating Python tkinter label in realtime - python

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.

Related

Function is not accessed

this is my code:
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
on hovering on on_enter_pressed function, it's showing function is not accessed and I'm getting the following error:
Traceback (most recent call last):
File "GUI.py", line 91, in <module>
app = ChatApplication()
File "GUI.py", line 15, in __init__
self._setup_main_window()
File "GUI.py", line 76, in _setup_main_window
self.msg_entry.bind("<Return>", self._on_enter_pressed)
AttributeError: 'ChatApplication' object has no attribute '_on_enter_pressed'
(I'm using tkinter in python to implement GUI.)
How can I solve this?
You have wrong indentations - _on_enter_pressed has to be outside __init__
def __init__(self):
# ... code ..
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
# outside `__init__`
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")

Kivy module in python

When I was trying to use grid layout, it shows errors when I try to use more widgets but with one widget it shows no errors,I have reviewed the codes many times but i didn't find any solutions,and by the way I'm using python 3.7 and kivy version 2 Here's my code:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
class My_Grid(GridLayout):
def __init__(self, **kwargs):
super(My_Grid, self).__init__(**kwargs)
self.cols = 4
self.rows = 3
self.add_widget(Label(text="First Name: "))
self.FirstName = TextInput(multiline=False)
self.add_widget(self.FirstName)
self.add_widget(Label(text="Last Name: "))
self.LastName = TextInput(mulyiline=False)
self.add_widget(self.LastName)
self.add_widget(Label(text="email: "))
self.Email = TextInput(mulyiline=False)
self.add_widget(self.Email)
class TestApp(App):
def build(self):
return My_Grid()
if __name__ == "__main__":
TestApp().run()
the errors when i use more widgets:
Traceback (most recent call last):
File "C:/Users/Asus/PycharmProjects/untitled3/my.py", line 29, in <module>
TestApp().run()
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\app.py", line 829, in run
root = self.build()
File "C:/Users/Asus/PycharmProjects/untitled3/my.py", line 25, in build
return My_Grid()
File "C:/Users/Asus/PycharmProjects/untitled3/my.py", line 18, in __init__
self.LastName = TextInput(mulyiline=False)
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\uix\textinput.py", line 527, in __init__
super(TextInput, self).__init__(**kwargs)
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\uix\behaviors\focus.py", line 367, in __init__
super(FocusBehavior, self).__init__(**kwargs)
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\uix\widget.py", line 350, in __init__
super(Widget, self).__init__(**kwargs)
File "kivy\_event.pyx", line 243, in kivy._event.EventDispatcher.__init__
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Process finished with exit code 1
At first, you have a mistake in the word 'multiline' in self.LastName and self.Email. Try to fix that.

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.

Getting a strange _tkinter.TclError: unknown option

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)

'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:

Categories

Resources