我正在对Tkinter项目进行测试,该项目将在软件中包含一些迷你游戏(有点像Mario paint)。对于此测试,我有2个框,一个为红色,另一个为蓝色,但是当它在红色框的旁边或内部时,它变为绿色。
这是代码。
from tkinter import *
from threading import Timer
window = Tk()
window.title("Canvas Test")
x = 30
y = 30
Test = Canvas(window,width = 1000,height = 1000)
Test.config(bg = "white")
Test.pack()
Move = Test.create_rectangle(x,y,x + 40,y + 40,fill = "blue")
Hitd = Test.create_rectangle(x,fill = "red")
Move = Test.create_rectangle(x,x + 30,y + 30,fill = "blue")
Test.update()
w = False
a2 = False
s = False
d = False
def KeyDown(event):
print("K Down")
global x
global y
global Move
global w
global a2
global s
global d
if event.char == "w" or event.char == "W":
w = True
elif event.char == "s" or event.char == "S":
s = True
if event.char == "a" or event.char == "A":
a2 = True
elif event.char == "d" or event.char == "D":
d = True
def KeyUp(event):
print("K Up")
global w
global a2
global s
global d
if event.char == "w" or event.char == "W":
w = False
elif event.char == "s" or event.char == "S":
s = False
if event.char == "a" or event.char == "A":
a2 = False
elif event.char == "d" or event.char == "D":
d = False
def MoveCheck():
global Move
global w
global a2
global s
global d
if w == True:
Test.move(Move,-10) #name,x mod,y mod
elif s == True:
Test.move(Move,10)
if a2 == True:
Test.move(Move,-10,0)
elif d == True:
Test.move(Move,10,0)
a = Test.bbox(Move)
b = Test.bbox(Hitd)
if b[0] in range(a[0],a[2]) or b[2] in range(a[0],a[2]) and b[1] in range(a[1],a[3]) or b[3] in range(a[1],a[3]):
Test.itemconfig(Move,fill = "green")
else:
Test.itemconfig(Move,fill = "blue")
t = Timer(0.03,MoveCheck)
t.start()
MoveCheck()
window.bind("<Key>",KeyDown)
window.bind("<KeyRelease>",KeyUp)
window.mainloop()
如果您与块成一直线,然后向下或向上移动1(或向左/向右移动,具体取决于您要在哪个轴上进行测试),则无论如何该块都会变为绿色。我对使用bbox极为陌生,因此这可能只是我的疏忽。