簡體   English   中英

Tkinter window 和 pygame window 同時打開

[英]Tkinter window and pygame window open at same time

I am trying to create a program that has a tkinter window open, and then when you push a button, it closes the tkinter window and opens a pygame window. However, when I click the button to open the pygame window, it opens the pygame window and the tkinter window stays open.

代碼:

import tkinter as tk
import pygame

root = tk.Tk()
btn = tk.Label(root, text="Start")
btn.bind("<Button-1>", lambda x: root.quit())
btn.pack()

root.mainloop()
root.destroy()

win = pygame.display.set_mode((500, 500))
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    win.fill((255, 255, 255))
    pygame.display.update()
pygame.quit()

我也嘗試過使用:

btn.bind("<Button-1>", lambda x: root.destroy())
btn.bind("<Button-1>", root.quit)
btn.bind("<Button-1>", root.destroy)
btn.bind("<Button-1>", lambda: root.quit())
btn.bind("<Button-1>", lambda: root.destroy())
def start(event=None):
    root.quit()
btn.bind("<Button-1>", start)

我怎樣才能解決這個問題? (我在 MacOS 11.1 上運行 Python 3.7.7)

我無法重現該問題。 但是我建議使用tkinter window 到 function 或 ZA2F2ED4F8EBC2CBB4C21A29DZ.40AB61 當按鍵被按下而不是在主循環退出后調用destroy 如果應用程序已經被銷毀,則調用destroy命令將導致錯誤,例如,如果 window 手動關閉。

import tkinter as tk
import pygame

def runTk():
    root = tk.Tk()
    btn = tk.Label(root, text="Start")
    btn.bind("<Button-1>", lambda x: root.destroy())
    btn.pack()
    root.mainloop()

runTk()

win = pygame.display.set_mode((500, 500))
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    win.fill((255, 255, 255))
    pygame.display.update()
pygame.quit()

我嘗試在 class 中組織您的代碼,因此對其進行修改和調用各個組件會更容易一些。

除此之外,我將您的btn更改為使用tk.Button而不是tk.Label (認為它在上下文中更有意義)

實際切換 function 調用self.tk_root.withdraw()命令。 這有效地隱藏了根 tk window - 您可以通過調用self.tk_root.deiconify()使其再次出現。 如果您還想在隱藏根之后銷毀它,您可以簡單地在撤銷后添加一個self.tk_root.destroy()

編輯:如果withdraw()不適合您,請嘗試使用iconify()代替。

import tkinter as tk
import pygame


class TkPygame:
    def __init__(self):
        self.tk_root = tk.Tk()

        self.make_tk_widgets()

        self.tk_root.mainloop()

    def make_tk_widgets(self):
        btn = tk.Button(self.tk_root, text='Start', command=self.toggle_to_pygame)
        btn.pack()

    def toggle_to_pygame(self):
        self.tk_root.withdraw()
        self.make_pygame_window()

    def make_pygame_window(self):
        pygame_root = pygame.display.set_mode((500, 500))
        run = True
        while run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
            pygame_root.fill((255, 255, 255))
            pygame.display.update()
        pygame.quit()


TkPygame()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM