前提・実現したいこと
マウスカーソルを動かすと銃のスコープが動き、それで画面上の物を射撃する といったゲームを作ろうとしています
とりあえず今のところはスコープがマウスカーソルを追いかけるのと、クリックしたら射撃した!という文章が表示される処理まで作りました
発生している問題・エラーメッセージ
GUI上でマウスを動かせばスコープの画像はマウスを追従して、マウスを動かした という文章が出力されます
クリックすれば BANG!という文章が出力されるのですが、どういったわけか出力しません
該当のソースコード
python
1import tkinter as tk 2import threading 3 4class GUI(object): 5 def __init__(self): 6 self.root=tk.Tk() 7 self.root.geometry("259x196+850+60") 8 #画像読み込み 9 self.BGImg=tk.PhotoImage(file="background.png") 10 self.ScopeImg=tk.PhotoImage(file="Scope.png") 11 12 self.Canvas = tk.Canvas(self.root,bg="white", width=400, height=350) 13 self.Canvas.bind("<Motion>",self.Move_Scope) 14 self.Canvas.pack() 15 #背景作成し、背景をクリックしたらshoot関数実行を設定 16 self.BG=self.Canvas.create_image(0, 0, image=self.BGImg,anchor=tk.NW) 17 self.Canvas.tag_bind(self.BG,"<Button-1>",self.shoot) 18 #スコープ作成 19 self.Scope=self.Canvas.create_image(-30, -37, image=self.ScopeImg) 20 21 self.root.mainloop() 22 23 def shoot(self,event): 24 print("BANG!") 25 26 def Move_Scope(self,event): 27 x, y = event.x, event.y #マウス座標取得 28 print("Mouse Moved") 29 threading.Thread(target=self.Move_Scope_Do,args=[x,y]).start() 30 31 def Move_Scope_Do(self,x,y): #以下スコープ画像移動のための処理 32 #画像の左上、右下の座標を合わせて2で割ることで画像の中央の座標取得 33 ScopeX=(self.Canvas.bbox(self.Scope)[0]+self.Canvas.bbox(self.Scope)[2])/2 34 ScopeY=(self.Canvas.bbox(self.Scope)[1]+self.Canvas.bbox(self.Scope)[3])/2 35 DifferentX=x-ScopeX #差を計算 36 DifferentY=y-ScopeY 37 self.Canvas.move(self.Scope,DifferentX,DifferentY) #差の分画像移動 38 39 40gui=GUI()
試したこと
スコープの移動処理に負担がかかりすぎているんじゃないかと思い、確かめてみるためにMove_Scope_Do関数の所を以下の様に無限ループで負担がかかるように書き換えてみました
でも無限ループさせていてもクリックしたら普通にBANG!という文章は出ます
上記の問題のあるコードでは、
threading.Thread(target=self.Move_Scope_Do,args=[x,y]).start()
の行を削除してスコープ処理をしないようにしたらBANG!という文章が出ます
一体Move_Scope_Do関数のどこに問題が隠れているのでしょうか?
指摘していただけると助かります
import tkinter as tk import threading class GUI(object): def __init__(self): self.root=tk.Tk() self.root.geometry("259x196+850+60") #画像読み込み self.BGImg=tk.PhotoImage(file="background.png") self.ScopeImg=tk.PhotoImage(file="Scope.png") self.Canvas = tk.Canvas(self.root,bg="white", width=400, height=350) self.Canvas.bind("<Motion>",self.Move_Scope) self.Canvas.pack() #背景作成し、背景をクリックしたらshoot関数実行を設定 self.BG=self.Canvas.create_image(0, 0, image=self.BGImg,anchor=tk.NW) self.Canvas.tag_bind(self.BG,"<Button-1>",self.shoot) #スコープ作成 self.Scope=self.Canvas.create_image(-30, -37, image=self.ScopeImg) self.root.mainloop() def shoot(self,event): print("BANG!") def Move_Scope(self,event): x, y = event.x, event.y print("Mouse Moved") threading.Thread(target=self.Loop).start() def Loop(self): while True: pass gui=GUI()
あなたの回答
tips
プレビュー