Skip to main content
 首页 » 编程设计

python之将变量传递给正在导入的文件

2025年02月15日8youxin

我有 3 个 Python 文件:login、teacher_ui 和 student_ui。所有这三个都使用 tkinter。登录文件将名称作为输入,如果该名称是数据库中的有效表,登录文件将导入 student_ui 文件以运行它。

我遇到的问题是 student_ui 文件需要一个名为 name 的变量,它是 login 中的输入。我正在努力将变量导入 student_ui,因为它一直在变化。

我在 login 中加载 student_ui 文件的代码是:

elif name_data in names_list: 
    opening_window.destroy() 
    import student_ui 

然后运行 ​​student_ui,它提供了一个不同的界面。 name_data 的代码是:name_data = name.get().lower()

student_ui 中需要name_data 的代码行是:user_table_name = name_data。此行抛出 NameError,因为 name 未定义。

因此,当 login 加载 student_ui 时,我如何让 student_ui 从 login 中获取 name_data ?

student_ui 的一些代码是:

number_words = { 
                        "Forty Five" : 45, 
                        ... 
                        "Nine Thousand, Eight Hundred and Sixty Four" : 9864 
} 
 
user_table_name = name_data 
 
query = 'SELECT _45 FROM {} ORDER BY runid DESC LIMIT  
3'.format(user_table_name) 
c.execute(query) 
status_1 = c.fetchall() 
if ('true',) in status_1: 
    status_1 = True 
else: 
    status_1 = False 

还有label、inputs、marking、大量数据库读写的代码。

请您参考如下方法:

根据 IsaacDj's comment : 我会使用类。

首先,我会将所有student_ui.py的代码封装到类中以防止意外的代码执行:

# student_ui.py 
 
class StudentUI: 
    def __init__(self, name): 
        self.name = name 
 
    def do_things(self): 
        number_words = { 
            "Forty Five" : 45, 
            ... 
            "Nine Thousand, Eight Hundred and Sixty Four" : 9864 
        } 
 
        query = 'SELECT _45 FROM {} ORDER BY runid DESC LIMIT 3'.format(self.name) 
 
        c.execute(query) 
        status_1 = c.fetchall() 
 
        if ('true',) in status_1: 
            status_1 = True 
        else: 
            status_1 = False 

为了简化操作,您可以直接导入 student-ui - 无需有条件地导入模块:

# login.py 
 
from student_ui import StudentUI 
 
def do_stuff(name_data): 
    if name_data in names_list: 
        opening_window.destroy() 
        student_ui = StudentUI(name_data) 
        student_ui.do_stuff() 
 
if __name__ == "__main__": 
    do_stuff() 

你也可以使用 if __name__ == "__main__":防止 student_ui 在导入时执行。