如何将一个Tkinter GUI嵌入另一个Tkinter GUI中?
这是我第一个图形用户界面(GUI):
#GUI1
import random, Id_generator, tkinter as tk
from tkinter import ttk
#constanst
STUDENTS = 15
TEACHERS = 4
def main():
#Main Window
app = tk.TK()
app.title('GUI1')
app.geometry('1000x600')
more code here...
app.mainloop()
def other_function()
code...
这是我的第二个图形用户界面(GUI2):
#GUI2
import GUI1, tkinter as tk,
from tkinter import ttk
#window
app = tk.Tk()
app.title('GUI2')
app.geometry('1400x800')
label_1 = ttk.Label(app, text ='imported gui')
label_1.pack()
gui_frame = tk.Frame(app)
gui_frame.pack(expand = True, fill = 'both')
gui_1_instance = GUI1.main()
gui_1_instance.pack(in_ = frame, expand = True, fill = 'both'
我想把GUI1嵌入到GUI2里面,这样当我运行GUI2的时候,GUI1就会显示在GUI2的窗口里。目前我尝试过的办法是把GUI1里的app.mainloop()这一行改成return(app)。但是到现在为止都没有成功。每次我运行GUI2的时候,都会打开两个窗口,分别是GUI1和GUI2,但GUI1并没有被放到GUI2里。
我该怎么把一个GUI嵌入到另一个GUI里面呢?用Tkinter可以做到吗?还是我应该换成PYQT?
2 个回答
1
把一个tkinter的图形界面嵌入到另一个tkinter的图形界面里其实很简单。因为你的代码不完整,我这里用另一个例子来说明。
from tkinter import *
#GUI to be embedded
def embed_gui(parent):
frame = Frame(parent)
frame.pack(side='top')
label = Label(frame, text="This is the embedded GUI")
label.pack(side='top')
btn = Button(frame, text="Submit")
btn.pack(side='top')
#GUI in which embedded into
def main():
root = Tk()
root.geometry('500x400')
# Embed using the function embed_gui
embed_gui(root)
root.mainloop()
#run main() if main is the main function and not the imported one.
if __name__ == "__main__": main()
1
你可以通过以下方式在一个框架里嵌入一个窗口:
- 在创建框架
gui_frame
时,设置container=True
- 在要嵌入的窗口上设置
use=gui_frame.winfo_id()
第一个界面:
import tkinter as tk
def main():
app = tk.Tk()
app.title('GUI1')
app.geometry('1000x600')
app.config(bg="pink")
tk.Label(app, text="Hello World", bg="pink").pack(padx=20, pady=20)
return app # return the window
第二个界面:
import tkinter as tk
from tkinter import ttk
import GUI1
app = tk.Tk()
app.title('GUI2')
app.geometry('640x480')
label_1 = ttk.Label(app, text ='imported gui')
label_1.pack()
gui_frame = tk.Frame(app, container=True) # set container=True
gui_frame.pack(expand=True, fill='both', padx=10, pady=10)
gui_1_instance = GUI1.main()
gui_1_instance.config(use=gui_frame.winfo_id()) # set use=...
app.mainloop()
结果:
注意:为了避免使用多个Tk
实例,嵌入的窗口最好使用Toplevel
。