Python程序在PyCharm中运行后,Tkinter窗口将自动关闭

2024-10-03 17:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用PyCharm编写一个小Python游戏。我用的是Macbook的Python3.4版。 游戏打开了一个窗口,并添加了一些东西。 然而,当运行游戏时,它会出现很短的时间并立即关闭。在

我在这里找到了一些关于Stackoverflow的提示,可以在游戏结束时添加输入(“按下关闭窗口”)。事实上,这确保了窗口不会立即关闭,但对于游戏来说并不实用。用户在游戏中需要使用箭头键。因此,在这种情况下添加输入(…)是没有用的。如何防止车窗自动关闭?谢谢!在

以下代码:

from tkinter import *

# Scherm maken
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title('Bellenschieter')
c = Canvas(window,width=WIDTH, height=HEIGHT, bg='darkblue')
c.pack()



# Duikboot maken
ship_id = c.create_polygon(5,5,5,25,30,15,fill='red')
ship_id2 = c.create_oval(0,0,30,30,outline='red')
SHIP_R = 15
MID_X = WIDTH/2
MID_Y = HEIGHT/2
c.move(ship_id, MID_X, MID_Y)
c.move(ship_id2, MID_X, MID_Y)

# Duikboot besturen
SHIP_SPD = 10
def move_ship(event):
    if event.keysym == 'Up':
        c.move(ship_id, 0, -SHIP_SPD)
        c.move(ship_id2, 0, -SHIP_SPD)
    elif event.keysym == 'Down':
        c.move(ship_id, 0, SHIP_SPD)
        c.move(ship_id2, 0, SHIP_SPD)
    elif event.keysym == 'Left':
        c.move(ship_id, -SHIP_SPD, 0)
        c.move(ship_id2, -SHIP_SPD, 0)
    elif event.keysym == 'Right':
        c.move(ship_id, SHIP_SPD, 0)
        c.move(ship_id2, SHIP_SPD, 0)
c.bind_all('<Key>', move_ship)

window.update()

input('Press <Enter> to end the program')

Tags: eventid游戏movewindowwidthid2height
1条回答
网友
1楼 · 发布于 2024-10-03 17:24:37

在设置小部件、事件处理程序之后启动事件循环。在

# input('Press <Enter> to end the program')  # (X)
window.mainloop()  # OR mainloop()

删除对input的调用。在

相关问题 更多 >