【发布时间】:2019-03-31 20:47:09
【问题描述】:
我对编程比较陌生,我注意到随着代码的增长,在 2 个文件(设置和主文件)中编写所有内容会变得非常混乱。 但是,当我将代码拆分为多个文件时,我遇到了无法导入 fileB.py intro FileA.py 并在文件 B 中使用文件 A 中的变量或小部件的问题(出现未定义名称错误)。
我在 UI 上使用 tkinter,所以我的主文件是 tk 循环 (main.py)。每个按钮指的是不同文件中的功能。它运行良好,直到我的函数包含按钮状态或条目文本。
这个例子是用 tkinter 的,但我在很多场合都遇到过这个问题,因为我相信我的代码结构。
文件 A (main.py)
import FileB
import tkinter
from tkinter import Checkbutton, Tk, Entry, BooleanVar
root = Tk() # initialize blank window
root.geometry("500x500")
# text entry
E1 = Entry(root, bd=5, width = 8)
E1.grid(row=0, column=1)
# Checkbox
CB_var = BooleanVar()
CB = Checkbutton(root, text="Get text", variable=CB_var, command=FileB.get_text() )
CB.grid(row=0, column=2)
root.mainloop()
文件B (FileB.py)
def get_text():
if CB.var == True:
entry_text = E1.get()
E1.config(state=DISABLED)
print(entry_text)
E1.delete(0, END)
elif CB.var == False:
E1.config(state=NORMAL)
print("Checkbox not selected")
由于在调用我的函数之前定义了 E1,我希望我的函数能够更改 E1 的状态,获取其文本并清空文本;就好像该函数在我的 main.py 中一样。
实际输出是未定义名称错误,因为 E1 不是我的 FileB 中的变量。
【问题讨论】:
标签: python file tkinter widget structure