[英]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.