如何在另一个模块中设置全局变量?

时间:2020-07-09 11:33:19

标签: python-3.x tkinter python-module

我想将一个实例(如指针)从我的主模块传递到另一个模块,因此我将能够更改我的主模块的入口值。在我的示例中-当用户单击按钮时,它使用lambda函数通过引用发送了对象,一切正常。

但是在calc.py模块中,我有很多功能。因此,我需要将入口对象附加到第二个模块中的所有按钮和接收功能上。

是否有一种简单的方法可以将入口对象的地址传递给第二个模块,所以那里的所有功能都将能够访问该对象(就像它们对于它们是全局的一样),而不必显式地将其传递给每个对象功能?

我附加了部分代码。我是Python的初学者。

MyApp.py

# module 1 (main)


import tkinter
import tkinter.ttk
from calc import* 


window = tkinter.Tk()

e1 = tkinter.ttk.Entry(frame5, width=62)
e1.grid()

insert7_btn = tkinter.ttk.Button(frame5, text="7", command=lambda: insert_num(7,e1))
insert7_btn.grid()

button_plus = tkinter.ttk.Button(frame5, text="+", command=lambda: memory('+',e1))
button_plus.grid()

....
....
window.mainloop()
  

calc.py

# module 2

import tkinter          
import tkinter.ttk
import math           

def insert_num(number,e1):
    .....


def memory(operation,e1):
    ..... 
......

1 个答案:

答案 0 :(得分:1)

我建议将所有函数放在calc.py中的一个类中,并在创建该类的实例时传递e1

# calc.py

class CalcUtils:
    def __init__(self, e1):
        self.e1 = e1

    def insert_num(self, number):
        # use self.e1 here
        ...
    
    def memory(self, operation):
        # use self.e1 here
        ...

然后在您的主应用程序中,以CalcUtils作为参数创建e1的实例,并使用该实例调用所需的函数:

import tkinter as tk
from tkinter import ttk
from calc import CalcUtils

window = tk.Tk()

e1 = ttk.Entry(window, width=62)
e1.grid()

utils = CalcUtils(e1)

insert7_btn = ttk.Button(window, text='7', command=lambda: utils.insert_num(7))
insert7_btn.grid()

button_plus = ttk.Button(window, text='+', command=lambda: utils.memory('+'))
button_plus.grid()

window.mainloop()