【问题标题】:How to access Tkinter window in another module?如何在另一个模块中访问 Tkinter 窗口?
【发布时间】:2021-05-19 10:55:00
【问题描述】:

我正在制作一个应用程序,其中窗口上有一个按钮,单击该按钮将调用同一程序中另一个模块中的函数。请帮我做。

ma​​in.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)

当我运行此代码时,没有任何反应。请告诉我可能是我的错误?

【问题讨论】:

  • 这和tkinter有什么关系?你应该重新学习python的基础知识。
  • 有几个问题: 1) bind 在空字符串上; 2)function1没有定义; 3) 没有在module1.py 中导入tkinter; 4) win 没有在module1.function() 中定义。
  • 如果你有我的目标,请帮助我实现它。

标签: python tkinter module


【解决方案1】:
  • 如果您想在module1.py 中引用function(),请使用module1.function,因为您使用import module1 来导入module1

  • 由于你使用了bind()function() 没有参数,所以你需要使用lambda 来执行它。建议使用command按钮选项而不是bind()

  • 你需要在module1.py中导入tkinter

  • win 无法在module1 中访问,您需要将其作为参数传递。

下面修改main.pymodule1.py

ma​​in.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)

【讨论】:

    猜你喜欢
    • 2015-11-19
    • 1970-01-01
    • 2018-05-11
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2016-09-23
    相关资源
    最近更新 更多