Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

python - tkinter getting variables from sub functions in other files to my gui?

I have made a small programme that processes and copies files for myself as practice. I have an issue regarding my tkinter GUI.

My programme consists of ~30 different functions in 8 different files. I have 3 types: GUI, controllers and functionality. Added to this, I have a file to define global variables.

A simplified example:

My function for declaring global variables:

## Global variables
def do_some():
    global counter
    counter=0

My model, here just a loop and something that gets returned. Note the counter, which should be a global variable.

#model    
def loop_model():
   import time
   import global_vars

   counter = 0

   for count in range(100):
       time.sleep(1)
    
       counter +=1
    
       messageToGive = f"I have run {counter} times"
    
    return messageToGive

For my controller, I have this very short code, just for calling the model

# controller
def loop_controller():
    import model
    import global_vars

    model.loop_model()

My GUI is as below. This small script works, except for the Label.config. I get ′NameError: name 'counter' is not defined′, as in, it doesn't recognise my global variable. What am I doing wrong here? I recognise I could change my structure to return my counter in this example, but not easily so in my real script.

# GUI
import tkinter as tk
import global_vars

global_vars.do_some()

root = tk.Tk()

root.geometry("800x600") # Size of the window
root.title("The no-duplicate Media Importer") # Main window title

def run_looper():
    import controller
    controller.loop_controller()

runButton = tk.Button(text="run this loop", height = 8, width = 40, command=run_looper)
runButton.pack()

counterLb = tk.Label(text="0 loops done")
counterLb.pack()

counterLb.config(text=f"{counter} loops done") ###causes NameError

root.mainloop()

I hope You can help,

GregersDK

question from:https://stackoverflow.com/questions/65600804/tkinter-getting-variables-from-sub-functions-in-other-files-to-my-gui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you write

import global_vars

Or

from global_vars import * 

It only copies the name defined in global_vars into the current module if you wanna get access and control global_vars then qualified way to do is

global_vars.counter += 1

Or

counterLb.config(text=f"{global_vars.counter} loops done") ### Should not give any error and work fine.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...