我正在制作一个应用程序,其中窗口上会有一个按钮,单击该按钮时将调用同一程序中另一个模块中的函数。请帮我这样做。
main.py
from tkinter import *
import module1
win = Tk()
button=Button(win,text="Button")
button.place(x=1,y=5)
button.bind("<ButtonPress-1>",function1)
win.geometry("1100x650")
mainloop()
module1.py
def function():
label=Label(win,text="Hii")
label.place(x=5,y=9)
当我运行这段代码时,什么也没有发生。请告诉我我的错误是什么?
答案 0 :(得分:1)
如果您想在 function()
中引用 module1.py
,请使用 module1.function
,因为您使用 import module1
导入 module1
。
由于您使用了 bind()
但 function()
没有参数,因此您需要使用 lambda
来执行它。建议使用按钮的 command
选项而不是 bind()
。
您需要在 tkinter
中导入 module1.py
。
win
无法在 module1
中访问,您需要将其作为参数传递。
下面是修改的main.py
和module1.py
:
main.py
from tkinter import *
import module1
win = Tk()
win.geometry("400x250")
button = Button(win, text="Button", command=lambda: module1.function(win))
button.place(x=1, y=5)
win.mainloop()
module1.py
from tkinter import *
def function(win):
label = Label(win, text="Hii")
label.place(x=50, y=90)