Neeraj Amoniya
Neeraj Amoniya

Reputation: 11

How to access Tkinter window in another module?

I am making an app in which there will be a button on the window which when clicked will call a function in another module in the same program. Please help me do that.

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)

When I run this code nothing happens. Please tell me what could be my mistake?

Upvotes: 0

Views: 945

Answers (1)

acw1668
acw1668

Reputation: 46688

  • If you want to reference function() in module1.py, use module1.function since you use import module1 to import module1.

  • Since you used bind() but function() does not have argument, so you need to use lambda to execute it. Suggest to use command option of button instead of bind().

  • You need to import tkinter in module1.py.

  • win cannot be accessed in module1, you need to pass it as an argument.

Below are modified main.py and 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)

Upvotes: 1

Related Questions