キャンバスtkinterでゲームブレイクアウトを作成していますが、バウンダリーを実行する条件を設定すると、パレットが移動しません。それが動くというステートメントを正しく書く方法は?
from tkinter import *
root = Tk()
root.title("Move Objects in canvas")
root.resizable(False,False)
height = 500
width = 700
x = width//2
y= height//2
can = Canvas(height = height, width=width,bg = "blue")
can.pack(pady = 30,padx=50)
rect = can.create_rectangle(height//2,700,width//2,490,fill = "green")
def keypress(event):
x,y = 0,0
if event.char == "a" and x > x:
x= -10
if event.char == "d" and x < 700 - width -x:
x= 10
can.move(rect,x,y)
root.bind("<Key>", keypress)
root.mainloop()
これを実現するには、長方形の座標を取得して、境界を確認します。
from tkinter import *
root = Tk()
root.title("Move Objects in canvas")
root.resizable(False,False)
height = 500
width = 700
x = width//2
y= height//2
can = Canvas(height = height, width=width,bg = "blue")
can.pack(pady = 30,padx=50)
rect = can.create_rectangle(height//2,700,width//2,490,fill = "green")
def keypress(event):
x1 = can.coords(rect)[0]
x2 = can.coords(rect)[2]
if event.char == "a" and x1 > 0:
x= -10
if event.char == "d" and x2 < 700:
x= 10
try:
can.move(rect,x,0)
except UnboundLocalError:
print('out of bounderies')
root.bind("<Key>", keypress)
root.mainloop()
また、境界外にあることを示すために、try andexceptブロックを追加しました。ご不明な点やエラーがございましたらお知らせください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加