在一个主文件中导入所有需要的模块,该文件包含导入模块所需的所有库
Importing all needed modules in one main file that has all needed libraries for modules imported
例如我有 2 个文件,mother.py 和 child.py,
child.py 是在 mother.py
中导入的模块
mother.py 中的代码是:
from tkinter import *
from tkinter import ttk
from modules.child import LoginWindow
root = Tk()
window = LoginWindow(root)
root.mainloop()
child.py 中的代码是:
class LoginWindow:
def __init__(self, master):
self.master = master
self.content = ttk.Frame(self.master, padding=(20,30,20,30))
当我这样做时,它给我一个错误,提示 tkk
(在 child.py 的最后一行)未定义,但在 mother.py(第 2 行)中定义) 为什么这不起作用,什么是使这样的东西起作用的最佳方法
Python 中的导入与其他语言中的 "include" 不同。整个模块包含在一个以您导入的模块命名的对象中。所以,当你这样做时:
from modules.child import LoginWindow
整个模块包含在 object/variable LoginWindow
中。在这种情况下,"child" 模块看不到导入它的模块中定义了哪些变量。
在你问题的例子中,你想移动:
from tkinter import ttk
至child.py
。
例如我有 2 个文件,mother.py 和 child.py, child.py 是在 mother.py
中导入的模块mother.py 中的代码是:
from tkinter import *
from tkinter import ttk
from modules.child import LoginWindow
root = Tk()
window = LoginWindow(root)
root.mainloop()
child.py 中的代码是:
class LoginWindow:
def __init__(self, master):
self.master = master
self.content = ttk.Frame(self.master, padding=(20,30,20,30))
当我这样做时,它给我一个错误,提示 tkk
(在 child.py 的最后一行)未定义,但在 mother.py(第 2 行)中定义) 为什么这不起作用,什么是使这样的东西起作用的最佳方法
Python 中的导入与其他语言中的 "include" 不同。整个模块包含在一个以您导入的模块命名的对象中。所以,当你这样做时:
from modules.child import LoginWindow
整个模块包含在 object/variable LoginWindow
中。在这种情况下,"child" 模块看不到导入它的模块中定义了哪些变量。
在你问题的例子中,你想移动:
from tkinter import ttk
至child.py
。