python - 将 tkinter GUI 与不同模块中的功能链接
问题描述
我想将 GUI(1. 模块)与不同模块中的功能链接起来。基本上我需要将 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 中的测试函数,如下所示:
模块1.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()
模块2.py:
def test(text_input):
text_input.set('hello')
不幸的是,python 真的不喜欢你做循环导入,这很好,因为这实际上意味着一个无限循环。它什么时候会停止导入其他文件?
编辑:将有一种非常复杂的方式在第三个模块中创建一个类并在其上设置属性,然后在 modul1 和 modul2 中导入第三个模块以在它们之间共享变量,但请不要......
Edit2:一个例子:
模块1.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()
模块2.py:
from shared import SharedClass
def test():
SharedClass.text_input.set('hello')
共享.py
class SharedClass:
pass
这是由于 python 加载导入的类的方式。他们都是一样的。这使得如果您在类(而不是它的实例)上设置属性,您可以共享属性。
推荐阅读
- docker - 由于没有可用的 Postgresql 实例,Spring Boot 和 Postgresql 应用程序在 docker 中构建失败
- javascript - 数组中的空元素不会被评估为未定义?
- php - 如何将 sweetalert 的输入值保存在数据库中以及如何将行从表移动到另一个
- excel - 如何将Excel表格拆分为多页Word文件
- amazon-web-services - 提供存储在 AWS S3 中的媒体文件的最佳方式
- python - 从动态导入模块中的父目录导入模块
- python - 为什么我必须一次又一次地关闭 pygame 窗口?
- analytics - 使用自定义变量进行 Matomo 跟踪得到总结/覆盖
- html - 在 Rshiny 仪表板中在背景图像上显示内容的问题
- angular - 将数据从父组件传递到子组件(包含响应式表单)以更新该表单的详细信息