简体   繁体   English

使用 tkinter 按钮在海龟中打开图像时出现错误“pyimage1”不存在

[英]I am having an error 'pyimage1' doesn't exist while opening image in turtle with tkinter button

Althogh it works perfectly fine with built in turtle shapes it doesn't work with new registered shapes.The error is pyimage1 doesn't exist and both my program and file are in the same directories Here is the code虽然它与内置的海龟形状完美配合,但它不适用于新注册的形状。错误是 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```




The problem is the way you're mixing turtle and tkinter is creating two roots which leads to this error.问题是您混合海龟和 tkinter 的方式正在创建两个导致此错误的根。 You're trying to use standalone turtle when you should be using embedded turtle.当您应该使用嵌入式海龟时,您正在尝试使用独立海龟。 Ie you should be using RawTurtle instead of Turtle and RawScreen instead of Screen .即你应该使用RawTurtle而不是TurtleRawScreen而不是Screen But don't just swap the names, look them up in the documentation.但不要只是交换名称,在文档中查找它们。 Your code should look roughly like:您的代码应大致如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM