简体   繁体   English

如何在 Tkinter 中打开同一文件的多个窗口?

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

I have a simple application in python.我在 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:到目前为止,这是我的文件 1 代码:

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. import file1将只导入file1 ,执行里面的代码file1次。 When import file1 is called again, nothing will happen because file1 has already been imported.当再次调用import file1时,不会发生任何事情,因为file1已经被导入。

To get around this, you can put the code inside a function and call that function after importing file1 :为了解决这个问题,您可以将代码放在一个函数中,并在导入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.但是,在file1导入file1不是一个好习惯,应该避免。


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调用import file1 file1 ,只需调用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:此外,在导入文件时更改添加.py扩展名:

import file1.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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