Reputation: 11
Here is my code:
from tkinter import *
import turtle as t
import random
bob=Tk()
t.setup(width = 200,height = 200)
t.bgpic(picname="snakesandladders.gif")
def left(event):
t.begin_fill()
print("left")
t.left(90)
def right(event):
print("right")
t.right(90)
def forward(event):
print("forward")
t.forward(100)
block = Frame(bob, width=300, height=250)
bob.bind("<a>", left)
bob.bind("<d>", right)
bob.bind("<w>", forward)
block.pack()
bob.mainloop()
And my error is:
Traceback (most recent call last):
File "/Users/lolszva/Documents/test game.py", line 6, in <module>
t.bgpic(picname="snakesandladders.gif")
File "<string>", line 8, in bgpic
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 1481, in bgpic
self._bgpics[picname] = self._image(picname)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 479, in _image
return TK.PhotoImage(file=filename)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3545, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3501, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "snakesandladders.gif": no such file or directory
I am a beginner so I don't really know if I did not import a library. In another, similar question for bgpic()
not working, it said to convert the picture to gif but for mine it still doesnt work. I'm using Mac OSX Python version 3.8.0.
Upvotes: 1
Views: 876
Reputation: 41905
Although your problem is a missing GIF file, your program will still fail even if the file exists, and is in the correct directory.
The secondary issue is that you invoke turtle standalone atop tkinter. You can either run turtle standalone where it sets up the underlying tkinter root and window, or you can run turtle embedded in tkinter where you setup the root and a canvas for turtle to roam. But invoking turtle standalone atop a tkinter root you created will fail with error:
...
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage2" doesn't exist
Here's how to implement your program in standalone turtle:
from turtle import Screen, Turtle
def left():
turtle.left(90)
def right():
turtle.right(90)
def forward():
turtle.forward(100)
screen = Screen()
screen.setup(width=200, height=200)
screen.bgpic(picname="snakesandladders.gif")
screen.onkey(left, "a")
screen.onkey(right, 'd')
screen.onkey(forward, 'w')
turtle = Turtle()
screen.listen()
screen.mainloop()
Put your GIF background image in the same directory as the source code.
You only need embedded turtle if you want to add tkinter widgets alongside the turtle canvas. See the documentation for RawTurtle
and TurtleScreen
.
Your window size is small compared to your forward()
distance -- you may need to adjust one or the other.
Upvotes: 1