Python - 如何在另一个文件的tkinter窗口中运行文件
我正在用pygame创建一个使用python的小游戏。Python - 如何在另一个文件的tkinter窗口中运行文件
有一个小问题: 我有我的界面在一个python文件和另一个文件中的游戏。 问题是,当我点击我的界面上的游戏时,它会在第二个窗口中加载游戏文件,并且我想在界面的当前窗口中执行此文件。 感谢您的时间!
有趣的部分代码:
接口文件(当点击独奏按钮,执行独奏定义)
def solo():
import Solo
fenetre.mainloop()
solo=Button(fenetre, image = pho15, width = 280, height = 81, borderwidth = 0, cursor = "hand2", command = solo)
独奏文件(生成一个新窗口)
fen=Tk()
fen.title("Super Crash")
coords = (175, 345)
image = Image.open("on.png")
photo = ImageTk.PhotoImage(image)
score=0
pygame.mixer.init()
crash = pygame.mixer.Sound("crash.ogg")
crash.set_volume(0.1)
bruit = pygame.mixer.Sound("bip.ogg")
bruit.set_volume(0.01)
ima1 = Image.open("Rejouer.jpg")
pho1 = ImageTk.PhotoImage(ima1)
ima2 = Image.open("Menu.jpg")
pho2 = ImageTk.PhotoImage(ima2)
can=Canvas(fen,bg="white", height=800, width=1000)
can.create_image(0,0, anchor = NW, image = photo)
can.focus_set()
can.bind("<KeyPress>", monter)
can.pack()
anim()
init()
的它创建另一个窗口的原因是因为fen = Tk()将创建一个新的应用程序窗口。如果你四处搜索,你可以找到一些这样做的例子,但是下面是如何在另一个内部启动外部tkinter应用程序。
主文件运行此文件(main.py或其他),并单击按钮
from tkinter import *
from subprocess import Popen
def launchExternal(parent):
container = Frame(parent, container=True)
container.pack(expand=True, fill='both')
''' Pass the window id of the container frame in this main application
to the external program. See solo.py for putting content in the
container.
'''
process = Popen(['python', 'solo.py', str(container.winfo_id())])
# Create the main application GUI (this file)
root = Tk()
# Define the external program name (will be solo.py)
program = 'solo'
# For fun, click this button multiple times to see what happens.
solo = Button(root, text="Launch solo", width = 10, height = 10, borderwidth = 0,
cursor = "hand2", command = lambda r=root: launchExternal(r))
solo.pack()
root.mainloop()
这是外部的(solo.py)文件。
from tkinter import *
import sys
def createInnerUI(master):
canvas = Canvas(master, bg='blue')
canvas.pack(pady=5)
label = Label(master, text="Demonstrate embedded application", bg='green')
label.pack()
if len(sys.argv) < 1:
root=Tk()
else:
target_window_id = sys.argv[-1]
root = Tk(use=target_window_id)
createInnerUI(root)
root.mainloop()
谢谢,所以完整的solo.py文件在createInnerUI函数中?它不适用于整个程序 –
不一定。如果您愿意,可以创建其他功能以将元素添加到GUI。例如,canvas可以在'root = Tk(use = target_window_id)'之后创建,并且在调用'createInnerUI(root)'之前创建,但是我选择将它放在带有标签的函数中。尝试移动的东西,看... –
至于*它不适用于整个程序*我不确定你的意思。 –
的[嵌入一个Pygame的窗口到TKinter或者wxPython的帧(https://stackoverflow.com/questions/23319059/embedding-a-pygame-window-into-a-tkinter-or可能的复制-wxpython-frame) –