動いているボールをマウスでクリックしたらスコアが1ずつ増えるようにしたいのですが、うまくいきません。
ボールは動いていますが、マウスでクリックしても反応しません。
エラーメッセージも表示されていないため、どこをどうすればいいのかわかりません。
数時間悩んでいるので、どなたか教えてください。
該当のソースコード
python
1import tkinter as tk 2import sys 3 4 #基本設定 5win_width = 600 #ウインドウサイズ(x) 6win_height = 400 #ウインドウサイズ(y) 7win_center_x = win_width/2 #画面のセンター(x座標) 8tick = 40 #ティック数(ミリ秒) 9 10root = tk.Tk() 11root.title("追いかけっこ") 12root.geometry("600x400") 13cv = tk.Canvas(root, width = win_width, height = win_height) #キャンバスの作成 14cv.pack() #パック 15 #基本設定 16 17 #ボールのクラス 18class Ball(): 19 x = 250 20 y = 250 21 w = 10 22 dx = dy = 2 23 color = "red" 24 def draw(self): 25 cv.create_oval(self.x-self.w, self.y-self.w, self.x+self.w, self.y+self.w, fill = self.color, tag = "ball") 26 cv.pack() 27 def move(self): 28 #移動 29 self.x += self.dx 30 self.y += self.dy 31 #ボールVS壁 32 if self.x - self.w < 0 or self.x + self.w > win_width: 33 self.dx *= -1 34 if self.y - self.w < 0 or self.y + self.w > win_height: 35 self.dy *= -1 36 def delete(self): 37 cv.delete("ball") 38 def M1(event): 39 if event == "ball": 40 score.score += 1 #スコアの加点 41 score.delete() #スコアを更新(削除-生成) 42 score.draw() 43 cv.update() 44 #self.x-self.w < event.x < self.x+self.w and self.y-self.w < event.y < self.y+self.w: 45 46#スコアのクラス 47class Score(): 48 score = 0 #スコアの初期値 49 def draw(self): 50 cv.create_text(win_width - 50, 50, text = "Score = " +str(self.score), font = ('FixedSys', 16), tag = "score") 51 def delete(self): 52 cv.delete("score") 53 54#インスタンス生成 55ball = Ball() #ボール 56score = Score() #スコア 57#インスタンス生成 58 59#初期描画 60ball.draw() #ボール 61score.draw()#スコア 62 63#初期描画 64 65#ゲームのメインループ 66def gameloop(): 67 ball.delete() #ボールを消す 68 ball.move() #ボールを動かす 69 ball.draw() #ボールを描く 70 root.after(tick, gameloop) #50ミリ秒経過後,ループの最初に戻る 71 #ゲームのメインループ 72 73def M2(event): 74 ball.M1() 75cv.bind("<Button>", M2) 76cv.place(x = 0, y = 0) 77cv.focus_set() 78cv.update() 79 #メインの実行部分 80gameloop() 81root.mainloop() #画面を表示 82 #メインの実行部分 83
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/08/15 07:09