当我尝试运行程序时,我收到了一个奇怪的错误。它应该在TK()窗口上绘制一个红色圆圈。
这是我的代码:
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()
我收到此错误:
File "C:\Python34\Lib\tkinter\__init__.py", line 2318, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: invalid command name ".37395760"
我已经重读了,甚至写下了我的代码,看看我哪里出错了,但我却找不到错误。
注意:运行此错误后,会出现一个带有黑色画布但没有圆圈的窗口。
谢谢!
答案 0 :(得分:2)
一旦mainloop退出(self.constructor.mainloop()
,小部件就不再存在了。当你执行self.canvas.create_oval(...)
(由c.drawPlayer()
触发)时,你正试图访问已删除的小部件。
Tkinter的设计并不是为了让您在主窗口被破坏后访问小部件。
完成元素绘制后调用mainloop()
。