Python: adding gif as turtle when integrating with tkinter

32 Views Asked by At

I currently have a snake game using turtle and the menu options using tkinter. When I click Play, the turtle opens in a new window. When I try to combine turtle and tkinter so it will open in the same window, I cannot keep my customized turtles or my background. I'm using VS Code. Can someone please help me?

Snake_menu.py


import Snake_unfinished
import tkinter as tk
import turtle
from tkinter import *
from PIL import Image, ImageTk
import customtkinter
import sys


def leave():
    sys.exit()

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master.title("Snake")
        self.pack()
        self.canvas = tk.Canvas(root)
        self.canvas.config(width=600, height=600)
        self.screen = turtle.TurtleScreen(self.canvas)
        self.Background()
    
    def Background(self):
        self.canvas = tk.Canvas(self, width=600, height=600)
        self.canvas.pack(expand='yes', fill='both')
        img = Image.open("ocean.png")
        self.photo = ImageTk.PhotoImage(img) 
        self.canvas.create_image(0, 0, anchor=NW, image=self.photo)
       
        self.canvas_id = self.canvas.create_text(100, 10, anchor=NW)
        self.canvas.itemconfig(self.canvas_id, text="Welcome to the Snake Game!", width=680)
        self.canvas.itemconfig(self.canvas_id, font=("courier", 20, 'bold'))

        play_button = customtkinter.CTkButton(root, text="PLAY", command = Snake_unfinished.main, width=200, height=100, compound="left",
                                           font=("courier", 30, 'bold'), fg_color="#50C878", hover_color="#92CA91", corner_radius=0)
        play_button_window = self.canvas.create_window(200,150, anchor=NW, window = play_button)


        exit_button = customtkinter.CTkButton(root, text="Exit", command=leave, width=200, height=100, compound="left",
                                           font=("courier", 30, 'bold'), fg_color="#D35B58", hover_color="#C77C78", corner_radius=0)
        exit_button_window = self.canvas.create_window(200,300, anchor=NW, window = exit_button)
        
           
if __name__ == '__main__':
    root = tk.Tk()
    app = App(root)
    app.mainloop()

Snake_unfinished.py

import turtle
from turtle import *
import time
import random
import pickle
import tkinter

def main():
    delay = 0.1
    score = 0

    #Get high score from file
    try:
        file = open('HighScore.dat','rb')
        high_score = pickle.load(file)
        file.close()

    # If no such file exists, set high_score to 0
    except:
        high_score = 0
    
    #tried adding this and changing all wn to screen, but didnt work
    '''root = tkinter.Tk()
    canvas = tkinter.Canvas(root)
    canvas.pack()
    screen = TurtleScreen(canvas)'''

    # Set up the screen
    wn = turtle.Screen()
    wn.title("Snake Game")
    wn.bgpic("ocean.gif") #Change background to water - must be .gif in python turtle
    wn.setup(width=600, height=600) #used free online pixel resizer to fit screen
    wn.tracer(0) # Turns off the screen updates

    #Hide cursor while playing game    
    c = turtle.getcanvas()
    c.config(cursor="none")

    # Snake head
    head = turtle.Turtle()
    head.speed(0)
    wn.addshape("snake_head_facingDown.gif") #Change head to snake
    head.shape("snake_head_facingDown.gif") #Use online gif background remover & online png to gif converter
    head.penup()
    head.goto(0,0)
    head.direction = "stop"

    # Snake food
    food = turtle.Turtle()
    food.speed(0)
    wn.addshape("minnow.gif") #Make food a minnow, resize, online png to gif converter, background remvoer
    food.shape("minnow.gif") 
    food.penup()
    food.goto(0,100)

    segments = []

    # Pen
    pen = turtle.Turtle()
    pen.speed(0)
    pen.shape("square")
    pen.color("black")
    pen.penup()
    pen.hideturtle()
    pen.goto(0, 260)
    pen.write(f"Score: {score}  High Score: {high_score}", align="center", font=("Courier", 16, "bold"))

    # Functions
    def go_up():
        if head.direction != "down":
            head.direction = "up"
            wn.addshape("snake_head_facingUp.gif") #Change snake head to face up, used online gif rotator
            head.shape("snake_head_facingUp.gif")

    def go_down():
        if head.direction != "up":
            head.direction = "down"
            wn.addshape("snake_head_facingDown.gif") #Change snake head to face down
            head.shape("snake_head_facingDown.gif")

    def go_left():
        if head.direction != "right":
            head.direction = "left"
            wn.addshape("snake_head_facingLeft.gif") #Change snake head to face left
            head.shape("snake_head_facingLeft.gif")

    def go_right():
        if head.direction != "left":
            head.direction = "right"
            wn.addshape("snake_head_facingRight.gif") #Change snake head to face right
            head.shape("snake_head_facingRight.gif")

    def move():
        if head.direction == "up":
            y = head.ycor()
            head.sety(y + 20)

        if head.direction == "down":
            y = head.ycor()
            head.sety(y - 20)

        if head.direction == "left":
            x = head.xcor()
            head.setx(x - 20)

        if head.direction == "right":
            x = head.xcor()
            head.setx(x + 20)

    # Keyboard bindings
    wn.listen()
    wn.onkeypress(go_up, "w")
    wn.onkeypress(go_down, "s")
    wn.onkeypress(go_left, "a")
    wn.onkeypress(go_right, "d")

    # Main game loop
    while True:
        wn.update()

        # Check for a collision with the border
        if head.xcor()>290 or head.xcor()<-290 or head.ycor()>250 or head.ycor()<-290: #Changed so snake cannot leave the water
            game_over()

        # Check for a collision with the food
        if head.distance(food) < 30: #Made bigger since fish is bigger pic
            # Move the food to a random spot
            x = random.randint(-290, 290)
            y = random.randint(-290, 250) #Changed so fish doesn't spawn out of water
            food.goto(x,y)

            # Add a segment
            new_segment = turtle.Turtle()
            new_segment.speed(0)
            wn.addshape("snake_body.gif") #Change body to match snake head, grabbed screenshot, online resizer
            new_segment.shape("snake_body.gif") 
            new_segment.penup()
            segments.append(new_segment)

            # Shorten the delay
            delay -= 0.001

            # Increase the score
            score += 10

            if score > high_score:
                high_score = score
                pen.color("red") 
            
            pen.clear()
            pen.write("Score: {}  High Score: {}".format(score, high_score), align="center", font=("Courier", 16, "bold"))

        # Move the end segments first in reverse order
        for index in range(len(segments)-1, 0, -1):
            x = segments[index-1].xcor()
            y = segments[index-1].ycor()
            segments[index].goto(x, y)

        # Move segment 0 to where the head is
        if len(segments) > 0:
            x = head.xcor()
            y = head.ycor()
            segments[0].goto(x,y)

        move()    

        # Check for head collision with the body segments
        for segment in segments:
            if segment.distance(head) < 20:
                game_over()

        def game_over():
            time.sleep(1)
            head.goto(0,0)
            head.direction = "stop"
            wn.clear()
            wn.bgcolor('black')
            pen.goto(0,0)
            pen.color("white") 
            pen.write("   GAME OVER \n Your Score is {}".format(score),align="center",font=("Courier",30,"bold"))
            time.sleep(2)
            turtle.bye()

        #Keep high score for next game
        file = open("HighScore.dat", "wb+")
        pickle.dump(high_score, file)
        file.close()

        time.sleep(delay)

    wn.mainloop()

I want the game to open in the same window as the menu without losing my turtle shapes (they're gifs) or background. I have tried looking at so similar questions on StackOverflow but I haven't found a solution.

0

There are 0 best solutions below