I am programming a small Python game in PyCharm. I am doing this on a Macbook with Python version 3.4. The game opens a Tkinter window and adds some stuff to it. However, when running the game, it shows up very briefly and closes immediately.
I found some tips here on Stackoverflow to add input('Press to close the window') at the end of the game. Indeed, this ensures that the window is not closed immediately, but it is not practical for the game. In the game, the user needs to use his arrow keys to play. So adding the input(...) is not useful in this case. How can I prevent the window to close automatically? Thanks!
Below the code:
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')
Start a event loop after setting up widgets, event handlers.
Remove the call to the
input
.