【问题标题】:Passing variable to file being imported?将变量传递给正在导入的文件?
【发布时间】:2017-06-04 15:37:38
【问题描述】:

我有 3 个 python 文件:loginteacher_uistudent_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_uilogin 中获取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

还有用于标签、输入、标记和大量数据库写入和读取的代码。

【问题讨论】:

  • 你的程序结构如何,运行不同的文件是什么?
  • login 文件运行格式不同的文件:if condition: import student_uielif other condition: import teacher_ui
  • UI 是用类等构建的还是只是代码?
  • 我会创建一个类并从模块中导入该类。在构造函数中,它将接收名称变量
  • 回复:@IsaacDj 建议:这将取决于代码的作用。其中一些可能必须移动到类的方法中——比如它的 __init__() 方法或您需要创建(并在某处调用)的新方法。

标签: python python-3.x variables python-import


【解决方案1】:

根据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 在导入时执行。

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多