简体   繁体   English

为什么tkinter给我一个“无效的命令名.37395760”错误?

[英]Why does tkinter give me an “invalid command name .37395760” error?

I'm getting a strange error when I try to run my program. 尝试运行程序时出现一个奇怪的错误。 It's supposed to draw a red Circle on a TK() window. 应该在TK()窗口上绘制一个红色的圆圈。

Here's my code: 这是我的代码:

from tkinter import *

class Circle:
    def __init__(self, radius, points = 0, xcoordinate = 0, ycoordinate = 0):    
        self.radius = radius
        self.points = points
        self.color = "red"
        self.xcoordinate = xcoordinate
        self.ycoordinate = ycoordinate

class World:
    def __init__(self):
        self.constructor = Tk()
        self.constructor.title("Circle")
        self.canvas = Canvas(self.constructor, width = 200, height = 200,     borderwidth = 0, highlightthickness = 0, bg = "black")
        self.canvas.grid()
        self.constructor.mainloop()

    def drawPlayer(self):
        player = Circle(50)
        self.canvas.create_oval(player.xcoordinate - player.radius, player.ycoordinate - player.radius, player.xcoordinate + player.radius, player.ycoordinate + player.radius, fill = player.color)

c = World()
c.drawPlayer()

I'm getting this error: 我收到此错误:

File "C:\Python34\Lib\tkinter\__init__.py", line 2318, in _create
    *(args + self._options(cnf, kw))))
_tkinter.TclError: invalid command name ".37395760"

I've reread and even wrote down my code to see where I was going wrong, but I just can't find an error. 我已经重新阅读,甚至写下了代码,以查看我要去哪里,但我只是找不到错误。

NOTE: This error happens after I run it and a window appears with a black canvas but no circle. 注意:我运行它后,会发生此错误,并且出现一个带有黑色画布但没有圆圈的窗口。

Thank you! 谢谢!

Once mainloop exits ( self.constructor.mainloop() , the widgets no longer exists. When you do self.canvas.create_oval(...) (which triggered by c.drawPlayer() ) , you're trying to access a deleted widget. 一旦mainloop退出( self.constructor.mainloop() ,小部件将不再存在。当您执行self.canvas.create_oval(...) (由c.drawPlayer()触发)时,您试图访问已删除的小部件。

Tkinter simply isn't designed to allow you to access widgets after the main window has been destroyed. Tkinter根本不被设计为允许您在主窗口被破坏之后访问小部件。

Call mainloop() after finish drawing your elements. 完成绘制元素后,调用mainloop()

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

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