简体   繁体   中英

How to open multiple windows of the same file in Tkinter?

I have a simple application in python. When I click a button it should open up the same file multiple times. However, after two times the program won't open any more windows.

Here is my code so far for file1:

from tkinter import *

root = Tk()
root.geometry("600x600")

def newWin():
   import file1

button = Button(root, text="Open Window of same file", command=newWin)
button.pack()

root.mainloop()

After clicking the button one time, it opens up the same file in a new window, but when I click the button in that window, it doesn't work. How do I fix this?

import file1 will only import file1 and execute the code inside file1 once. When import file1 is called again, nothing will happen because file1 has already been imported.

To get around this, you can put the code inside a function and call that function after importing file1 :

# file1.py
import tkinter as tk

def main():
    root = tk.Tk()
    root.geometry('600x600')

    def new_win():
        import file1
        file1.main()

    button = tk.Button(root, text='Open Window of same file', command=new_win)
    button.pack()

    root.mainloop()

if __name__ == '__main__':
    main()

However, importing file1 inside file1 is not a good practice and should be avoided.


The above code is just a demo of fixing the import issue. Actually you don't need to call import file1 inside file1 , just call main() :

# file1.py
import tkinter as tk

def main():
    root = tk.Tk()
    root.geometry('600x600')

    button = tk.Button(root, text='Open Window of same file', command=main)
    button.pack()

    root.mainloop()

if __name__ == '__main__':
    main()

Your button has no command parameter, otherwise, it will do nothing.

button = Button(root, text="Open Window of same file", command = newWin)

Also, change add the .py extension while importing your file:

import file1.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM