I'm still trying to figure out how to separate my UI from my programme logic. I'm fairly new to Python and maybe you can help me out.
I was trying to separate my UI from my programme hoping that I might be able to switch from tkinter to some other GUI later on. So I was thinking to have my main programme doing stuff and calling a tk Frame for displaying my data.
So, this is my class for displaying and it works fine:
import tkinter as tk
class TestClass(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.label1 = tk.Label(text="Label1")
self.label1.pack()
self.changeLabel1("change from within") # <-- this works
def changeLabel1(self, changeText):
self.label1.config(text=changeText)
self.update_idletasks()
def writeSomething(self, outputText):
print(outputText)
And I made myself some test programme to instantiate the class:
# starter for TestClass
import TestClass
x = TestClass.TestClass()
x.mainloop()
x.writeSomething("Test") <-- nothing happens
x.changeLabel1("Test") <-- nothing happens
I put those calls to the functions after the mainloop just to show that I'm not able to change something after the mainloop has been called.
When I'm trying to change the label1 with the changeLabel1 function it works from within the class but not from my starter class. I get some output from writeSomething(text) but only when I close the window. And there is an error message which reads:
_tkinter.TclError: invalid command name ".!label"
(It is actually longer, only the last line of the traceback.)
Searching brought me to the conclusion that it might have something to do with the mainloop() but I'm not sure how to handle this problem.
What is best practice? Do I call the mainloop in my tkinter class or in my test file which calls the tkinter class?
Is this a way to separate UI and logic or am I getting something wrong and should it be done the other way around (calling the programme logic from within the UI class)?
I hope I made myself clear enough...
x.mainloop()at the very end of your program.