我一直在尝试使用tkinter在类中创建一个按钮,但按钮不会出现。剩下的比赛很好。我就是当我尝试在游戏类中添加退出按钮时它不会出现。我使用的是python 3.4.3。我正在做一个游戏,你用潜水艇弹出气泡。我试过了self.button_quit = tkinter.Button(window, text="Quit")
,这是类代码:
class Game():
height = 500
width = 800
mid_x = width / 2
mid_y = height / 2
bonus_score = 700
bubble_chance = 10
gap = 100
time_limit = 30
speed = 0.01
def __init__(self):
self.score = 0
self.bonus = 0
self.window = tkinter.Tk()
self.window.title('Bubble Blaster')
self.canvas = tkinter.Canvas(self.window, width=self.width,
height=self.height, bg='darkblue')
self.end = time.time() + self.time_limit
Text(self.canvas,50,30,'TIME')
Text(self.canvas,150,30,'SCORE')
self.gui_score = Text(self.canvas,150,50)
self.gui_time = Text(self.canvas,50,50)
self.canvas.pack()
self.bubbles = list()
self.ship = Ship(self.canvas)
self.ship.move(self.mid_x, self.mid_y)
def coords_of(cid):
pos = c.coords(cid)
x = (pos[0] + pos[2]) / 2
y = (pos[1] + pos[3]) / 2
return x, y
def create_bubble(self):
x = self.width + self.gap
y = random.randint(0,self.height)
self.bubbles.append(Bubble(self.canvas,x,y))
def move_bubbles(self):
for bubble in self.bubbles:
bubble.move(-bubble.speed,0)
def destroy_bubble(self,bubble):
self.bubbles.remove(bubble)
bubble.destroy()
def clean_up_bubbles(self):
for bubble in self.bubbles:
if bubble.x < -self.gap:
self.destroy_bubble(bubble)
def buttons(self):
self.button1 = tkinter.Button(window, text="Quit")
self.button1.tkinter.pack()
def run(self):
while time.time() < self.end:
if random.randint(1, self.bubble_chance) == 1:
self.create_bubble()
self.move_bubbles()
self.clean_up_bubbles()
self.score += self.ship_bubble_collision()
if (int(self.score / self.bonus_score)) > self.bonus:
self.bonus += 1
self.end += self.time_limit
self.time_left = int(self.end - time.time())
self.update_gui()
self.window.update()
self.ship.step()
time.sleep(self.speed)
Text(self.canvas,self.mid_x, self.mid_y,'GAME OVER',
font=('Helvetica',30))
Text(self.canvas,self.mid_x, self.mid_y + 30,
'Score ' + str(self.score))
Text(self.canvas,self.mid_x, self.mid_y + 45,'Bonus Time ' +
str(self.bonus * self.time_limit))
input()
def distance(self,x1,y1,x2,y2):
return math.sqrt((x2-x1)**2+(y2-y1)**2)
def ship_bubble_collision(self):
points = 0
for bubble in self.bubbles:
distance = self.distance(self.ship.x,self.ship.y,\
bubble.x,bubble.y)
boundary = self.ship.radius + bubble.radius
if distance < boundary:
points += bubble.radius + bubble.speed
self.destroy_bubble(bubble)
return points
def update_gui(self):
self.gui_score.update(str(self.score))
self.gui_time.update(str(self.time_left))
if __name__ == '__main__':
Game().run()