我有一个python代码。我在Windows 10上尝试使用python 2.x中的Tkinter
有一个500 x 500的窗户
然后有一个延伸线程的Food类。线程。
Food的任务是在画布上创建20000个椭圆形
还有一个Ship类,其任务是在画布上绘制并移动一个蓝色矩形。船级不扩展任何类
但有一个问题。当我运行程序时,Food开始在画布上创建食物。但是当我移动我的船时,在一些运动程序发出错误并且食物停止产生椭圆形,但是船继续移动
有什么问题?
错误是:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Users\PC\EclipseWorkspace\PyTests\main.py", line 37, in run
self.random_oval()
File "C:\Users\PC\EclipseWorkspace\PyTests\main.py", line 30, in random_oval
self.oval = self.canvas.create_oval(x-5,y-5,x+5,y+5)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2320, in create_oval
return self._create('oval', args, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2305, in _create
*(args + self._options(cnf, kw))))
ValueError: invalid literal for int() with base 10: 'expected boolean value but got "??"'
以下是代码:
from Tkinter import *
from Queue import Queue
import threading as th
import time
import random
wnd = Tk()
wnd.geometry("500x500+100+100")
canvas = Canvas(wnd, bg="yellow")
canvas.pack(expand=YES, fill=BOTH)
class Food(th.Thread):
def __init__(self, canvas,food_count):
canvas.update()
self.width, self.height = canvas.winfo_width(), canvas.winfo_height()
self.food_count = food_count
self.canvas = canvas
self.points = []
self.random_oval()
th.Thread.__init__(self)
self.start()
def random_oval(self):
while True:
x = random.randrange(0,self.width)
y = random.randrange(0,self.height)
if (x,y) not in self.points : break
self.oval = self.canvas.create_oval(x-5,y-5,x+5,y+5)
self.points.append((x,y))
def run(self):
count = 0
while count != self.food_count:
self.random_oval()
count += 1
time.sleep(0.001)
class Ship:
def __init__(self,x,y, canvas):
self.x, self.y = x,y
self.canvas = canvas
self.ship = self.canvas.create_rectangle(self.x, self.y,self.x+10,self.y+10,fill="blue")
def move(self,event):
direction = event.keysym.lower()
if direction not in ["left", "right", "up", "down"] : return None
if direction == "right" : self.x += 10
elif direction == "left" : self.x -= 10
elif direction == "up" : self.y -= 10
else : self.y += 10
self.ship = self.canvas.create_rectangle(self.x, self.y,self.x+10,self.y+10,fill="blue")
Food(canvas, 20000)
ship = Ship(50,50,canvas)
wnd.bind("<Key>",lambda e: ship.move(e))
wnd.mainloop()