完全可以与内置的乌龟形状完美配合 新注册的形状。错误是pyimage1不存在,并且我的程序和文件都在同一目录中 这是代码
root=Tk()
import turtle
def image():
global img
img='batman.gif'
player=turtle.Turtle()
wn=turtle.Screen()
wn.register_shape(img)
player.shape(img)
B=Button(root,text='click',command=image).pack()```
The error shown is:```Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\dell\OneDrive\Desktop\imagetk.py", line 10, in image
player.shape(img)
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 2777, in shape
self.turtle._setshape(name)
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 2506, in _setshape
self._item = screen._createimage(screen._shapes["blank"]._data)
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 723, in _createimage
return self.cv.create_image(0, 0, image=image)
File "<string>", line 1, in create_image
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2489, in create_image
return self._create('image', args, kw)
File "C:\Users\dell\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2480, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage1" doesn't exist```
答案 0 :(得分:1)
问题是您混合使用turtle和tkinter的方式正在创建两个导致此错误的根。当您应该使用嵌入式乌龟时,尝试使用独立乌龟。即您应该使用RawTurtle
代替Turtle
,使用RawScreen
代替Screen
。但是,不只是交换名称,而是在文档中查找它们。您的代码应大致如下:
from tkinter import *
from turtle import TurtleScreen, RawTurtle
IMAGE = 'batman.gif'
def image():
player = RawTurtle(screen)
player.shape(IMAGE)
root = Tk()
Button(root, text='click', command=image).pack()
canvas = Canvas(root)
canvas.pack()
screen = TurtleScreen(canvas)
screen.register_shape(IMAGE)
screen.mainloop()