繁体   English   中英

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

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

我在 python 中有一个简单的应用程序。 当我单击一个按钮时,它应该多次打开同一个文件。 但是,两次后该程序将不再打开任何窗口。

到目前为止,这是我的文件 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()

单击该按钮一次后,它会在新窗口中打开同一个文件,但是当我单击该窗口中的按钮时,它不起作用。 我该如何解决?

import file1将只导入file1 ,执行里面的代码file1次。 当再次调用import file1时,不会发生任何事情,因为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()

但是,在file1导入file1不是一个好习惯,应该避免。


上面的代码只是修复导入问题的演示。 实际上,您不需要在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()

你的按钮没有命令参数,否则它什么都不做。

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

此外,在导入文件时更改添加.py扩展名:

import file1.py

暂无
暂无

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

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