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

Ber*_*ans 2 python tkinter pycharm python-3.x

我正在 PyCharm 中编写一个小型 Python 游戏。我正在使用 Python 3.4 版本的 Macbook 上执行此操作。游戏会打开一个 Tkinter 窗口并向其中添加一些内容。但是,运行游戏时,它会显示非常短暂并立即关闭。

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

代码如下:

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')
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 7

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

# input('Press <Enter> to end the program')  # (X)
window.mainloop()  # OR mainloop()
Run Code Online (Sandbox Code Playgroud)

删除对 的调用input