I'm running a threaded program using tkinter, using different files to separate the program logic:
### File Solution_Name.py ############
import Form_Main as F
from tkinter import *
import tkinter as tk
root = tk.Tk()
app = F.Form_Main(root)
root.mainloop()
### File Form_Main.py ###############
import Program_Logic
import tkinter as tk
from tkinter import *
import threading
class Form_Main:
def __init__(self, root):
#Window
root.title("Main Window")
root.geometry('1200x600')
def main_thread():
Program_Logic.do_tasks()
threading.Thread(target=main_thread).start()
label_1=tk.Label(root, text = "Initial Label Text").place(x=20, y=20)
### File Program_Logic.py ################
import threading
def do_tasks():
while True:
# Program Logic
#
#
label_1.config(text="New Text")
I'm wanting to change the text in label_1 from within the do_tasks() method in Program_Logic.py. The above code doesn't work because label_1 is out of scope. I have tried several things to refer to label_1 from do_tasks():
- Referring to Form_Main i.e. Form_Main.label_1.config(text="New Text") This fails because it can't see label_1 because it's within the init in Form_Main
- Putting a function in Form_Main to change label_1. This fails because it will not refer to label_1 unless it has 'self', and I can't find a way of passing the correct 'self' from do_tasks()
- Putting a function in init within Form_Main. This fails because I can't refer to that function from do_tasks()
- Make label_1 global, either by using the global keyword, or having it first defined in a separate globals file (which I use for other threading logic). This has the unexpected behavior of label_1 being equal to None immediately after the line label_1=tk.Label(root, text = "Initial Label Text").place(x=20, y=20) so it throws an error when attempting to change the text on a None object.
Is there a way to change the text of label_1 from within the do_tasks() method?