我想将 GUI (1.modul) 与不同模块中的功能链接起来。基本上我需要将 GUI 与程序链接起来。
我创建了一个非常简单的示例:
模块1:
from modul2 import *
from tkinter import *
window = Tk()
window.title('Program')
window.geometry("300x300")
text_input= StringVar()
#result
result=Entry(window, textvariable=text_input)
result.place(x=6,y=15)
#Button
button=Button(window, text='X')
button.config(width=5, height=2, command=lambda: test())
button.place(x=10,y=70)
window.mainloop()
模块2:
import modul1
def test():
global text_input
text_input.set('hello')
预计: 该程序应在单击按钮后将“hello”写入输入窗口。
结果:错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Ondrej\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/Ondrej/Desktop/VUT FIT/IVS\modul1.py", line 17, in <lambda>
button.config(width=5, height=2, command=lambda: test())
NameError: name 'test' is not defined
有人知道问题出在哪里吗? 预先感谢您的帮助。
最佳答案
是的,您实际遇到的问题与循环导入有关。 Modul1 导入 Modul2,Modul2 导入 Modul1。解决这个问题的一种方法是将 textinput 作为参数提供给 modul2 中的测试函数,如下所示:
modul1.py:
import modul2
from tkinter import *
window = Tk()
window.title('Program')
window.geometry("300x300")
text_input = StringVar()
# result
result = Entry(window, textvariable=text_input)
result.place(x=6, y=15)
# Button
button = Button(window, text='X')
button.config(width=5, height=2, command=lambda: modul2.test(text_input))
button.place(x=10, y=70)
window.mainloop()
modul2.py:
def test(text_input):
text_input.set('hello')
不幸的是,Python 确实不喜欢你进行循环导入,这很好,因为这实际上意味着无限循环。什么时候停止导入其他文件?
编辑:有一种非常复杂的方法可以在第三个模块中创建一个类并为其设置属性,然后在 modul1 和 modul2 中导入第三个模块以在它们之间共享变量,但请不要...
Edit2:一个例子:
Modul1.py:
from shared import SharedClass
import modul2
from tkinter import *
window = Tk()
window.title('Program')
window.geometry("300x300")
SharedClass.text_input = StringVar()
# result
result = Entry(window, textvariable=SharedClass.text_input)
result.place(x=6, y=15)
# Button
button = Button(window, text='X')
button.config(width=5, height=2, command=lambda: modul2.test())
button.place(x=10, y=70)
window.mainloop()
Modul2.py:
from shared import SharedClass
def test():
SharedClass.text_input.set('hello')
共享.py
class SharedClass:
pass
这是由于 python 加载导入类的方式而起作用的。他们都是一样的。这使得如果您在类(而不是它的实例)上设置属性,您就可以共享这些属性。
关于python - 将 tkinter GUI 与不同模块中的函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55547698/