0
當我在tkinter中創建一個對象時,我如何通過該對象中的嵌入命令使對象破壞自己? 代碼是這樣的;我正在編寫一個收集硬幣的遊戲 我想在收集它們後讓硬幣消失。蟒蛇 - 如何使對象'自殺'?
from tkinter import*
import time
import random
import math
color=['gray','skyblue','orange','green','yellow','blue']
score=[0,0,0,0,0,0]
class Player:
//player class. with wasd keys
class Coin:
def __init__(self,canvas,player,i):
self.Color=color[i]
self.canvas=canvas
self.player=player
self.id=canvas.create_rectangle(10,10,20,15,fill=self.Color,state='normal',width=0)
self.canvas_width=self.canvas.winfo_width()
self.canvas_height=self.canvas.winfo_height()
self.x=random.randint(0,self.canvas_width-50)
self.y=random.randint(0,self.canvas_height-50)
self.canvas.move(self.id,self.x,self.y)
self.i=i
self.GetC=False
def draw(self):
self.canvas.move(self.id,self.x,self.y)
pos=self.canvas.coords(self.id)
if pos[1]<=0:
lv=random.randint(1,3)
self.y=lv*self.i
if pos[3]>=self.canvas_height:
lv=random.randint(-3,-1)
self.y=lv*self.i
if pos[0]<=0:
lh=random.randint(1,3)
self.x=lh*self.i
if pos[2]>=self.canvas_width:
lh=random.randint(-3,-1)
self.x=lh*self.i
if self.hit_player(pos)==True:
self.GetC=True
def hit_player(self,pos):
player_pos=self.canvas.coords(self.player.id)
if pos[2]>=player_pos[0] and pos[0] <=player_pos[2]:
if pos[3]>=player_pos[1] and pos[1]<= player_pos[3]:
return True
return False
def scoring(self):
if self.GetC==True:
score[0]=round(score[0]+0.01*pow(2,self.i),2)
score[self.i]=round(score[self.i]+0.01,2)
self.GetC=False
tk=Tk()
tk.title("GAME")
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
canvas=Canvas(tk,width=500,height=400,bd=0,highlightthickness=0)
canvas.pack()
tk.update()
player=Player(canvas,'blue')
coin=[]
for k in range(50):
l=6-int(math.log2(random.randint(2,32)))
coin.append(Coin(canvas,player,l))
inv=canvas.create_text(250,200,text=score,state='hidden')
while 1:
if player.Toggle==True:
canvas.itemconfig(inv,state='normal')
if player.Toggle==False:
canvas.itemconfig(inv,state='hidden')
for k in range(50):
coin[k].scoring()
coin[k].draw()
canvas.itemconfig(inv,text=score)
if player.Q==True:
break
player.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)
如果硬幣在畫布上繪製的,你應該檢查'canvas.delete'方法。我還建議您使用'tk.after'而不是'time.sleep',因爲後者會在睡眠時間內使窗口無響應。 –