0

I am trying to create Snake game but tkinter window closes before i can see anything i have used turtle.mainloop(), but still no use

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()

I use Visual Studio Code as editor Please let me know how i can stop this And looks like, it not the code but something else

Ash
  • 63
  • 8
  • 2
    Can you please how us some minimal working code so that we can test it out? For example I don't know if `turtle` is the python module named `turtle` or a `` window named `turtle` – TheLizzard Apr 24 '21 at 17:23
  • Please read how to create [mre] – Matiiss Apr 24 '21 at 17:30
  • @Matiiss i have update the question with minimal code, please have a look – Ash Apr 24 '21 at 18:13
  • 1
    @Ash `wn.canvheight` is a python `int`. It isn't the correct way to set the turtle screen height. Look [here](https://stackoverflow.com/a/56530216/11106801) for more info. TL;DR use `screen.setup(width, height)` instead of `wn.canvheight = 200` and `wn.canvwidth(300)` – TheLizzard Apr 24 '21 at 19:21
  • @t Thank you. `screen.setup(width, height)` worked – Ash Apr 25 '21 at 09:30

1 Answers1

0

Tkinter 'mainloop' is a continually running function from the class Tk(). Creating an instance of Tk initializes Tk's interpreter and creates the root window. The main window and this interpreter are linked, and both are required for your program to work.

Example:

from tkinter import *


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

root.mainloop()
  • 1
    Did you notice that OP is using the `turtle` module which creates the window? Also I don't know if `root.title = "Snake Game"` will work. `root.title("Snake Game")` is better – TheLizzard Apr 24 '21 at 20:18