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

编程入门 行业动态 更新时间:2024-10-28 21:21:46
本文介绍了Python 程序在 PyCharm 中运行后,Tkinter 窗口会自动关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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.

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

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!

代码下方:

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.

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

移除对input的调用.

这篇关于Python 程序在 PyCharm 中运行后,Tkinter 窗口会自动关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 06:35:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自动关闭   窗口   程序   Python   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!