首页 > 解决方案 > 将 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

有谁知道问题出在哪里?预先感谢您的帮助。

标签: pythonpython-3.xtkinter

解决方案


是的,您实际遇到的问题与循环导入有关。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 加载导入的类的方式。他们都是一样的。这使得如果您在类(而不是它的实例)上设置属性,您可以共享属性。


推荐阅读