【问题标题】:Tkinter Window closes imediatedly before i see the resultsTkinter 窗口在我看到结果之前立即关闭
【发布时间】:2021-04-24 17:13:09
【问题描述】:

我正在尝试创建 Snake 游戏,但 tkinter 窗口在我看到任何内容之前关闭 我用过turtle.mainloop(),还是没用

import turtle as t
import random as rd
import time as ti

wn = t.Screen()
wn.bgcolor('yellow')
wn.title('Snake game')
wn.canvheight(200)
wn.canvwidth(300)

snake = t.Turtle()

scores = t.Turtle()

text = t.Turtle()


leaf = t.Turtle()

def start():
    pass


def down_move():
    if snake.heading() == 0 or snake.heading() == 180:
        snake.setheading(270)
    
def up_move():
    if snake.heading() == 0 or snake.heading() == 180:
        snake.setheading(90)

def left_move():
    if snake.heading() == 90 or snake.heading() == 270:
        snake.setheading(180)

def right_move():
    if snake.heading() == 90 or snake.heading() == 270:
        snake.setheading(0)


text.write("Start the game", align = "center", font=("Arial", 50, "bold"))
wn.onkey(start, "space")
wn.onkey(down_move,"Down")
wn.onkey(up_move,"Up")
wn.onkey(left_move,"Left")
wn.onkey(right_move,"Right")
wn.listen()

wn.mainloop()

我使用 Visual Studio Code 作为编辑器 请让我知道如何阻止这种情况 看起来,它不是代码,而是其他东西

【问题讨论】:

  • 您能否请教我们一些最小的工作代码以便我们测试它?例如我不知道turtle是名为turtle的python模块还是名为turtle<tkinter.Tk>窗口
  • 请阅读如何创建minimal reproducible example
  • @Matiiss 我已经用最少的代码更新了问题,请看一下
  • @Ash wn.canvheight 是 python int。这不是设置海龟屏幕高度的正确方法。查看here 了解更多信息。 TL;DR 使用 screen.setup(width, height) 而不是 wn.canvheight = 200wn.canvwidth(300)
  • @t 谢谢。 screen.setup(width, height) 工作

标签: python tkinter


【解决方案1】:

Tkinter 'mainloop' 是 Tk() 类中一个持续运行的函数。创建 Tk 的实例会初始化 Tk 的解释器并创建根窗口。主窗口和这个解释器是链接在一起的,这两者都是您的程序运行所必需的。

例子:

from tkinter import *


root = Tk()
root.title = "Snake Game"

root.mainloop()

【讨论】:

  • 您是否注意到 OP 正在使用创建窗口的turtle 模块?另外我不知道root.title = "Snake Game" 是否有效。 root.title("Snake Game") 更好
猜你喜欢
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2021-02-24
  • 2020-11-08
相关资源
最近更新 更多