我正在制作一款带有10英寸触摸屏的覆盆子pi的游戏,我决定使用Tkinter来与pi进行交互。 目前,一旦用户选择了他们的游戏模式,并且他们被带到这个屏幕,我然后尝试在这个屏幕上放置一个标签显示他们的当前级别,代码运行,tkinter窗口停止响应,但命令行中的代码仍在继续。 以下是在生存屏幕上运行的代码:
def start_survival(game):
while game.health != 0:
print(str(game.level))#for Testing
lbl = Label(root, text=lbBlue, font=SMALL_BUTTON_FONT)
lbl['text'] = 'level: ' + str(game.level)
lbl.place(x=35, y=15)
print('Where is: ' + str(game.newDistance())+ ' and allowance is: ' + str(game.allowance))
#game.newDistance()
#count down
game.measureDistance()
if game.playerDistance >= game.lowerBound() and game.playerDistance <= game.upperBound():
game.level += 1
print('NEXT LEVEL')
else:
game.health -= 1
print('Ouch! You just lost a life your health is now: ' + str(game.health))
#u guessed ..... which is not in the range ..... ----> little diagram
game.allowance = int(game.allowance*0.90)
if game.allowance > 5:
game.allowance = int(game.allowance*0.90)
所以上述所有内容都来自:
game = gamemode_normal()
root.after(100, lambda: start_survival(game))
如果有人对可能存在的问题有任何想法,请分享! 谢谢汤姆
答案 0 :(得分:0)
您需要在放置标签后更新显示,因为您的代码仍在运行。无需手动运行root.update()
,Tkinter会在更新显示内容之前等待代码完成。这就是当你用Ctrl-C结束程序时出现的原因。这是新代码:
def start_survival(game):
while game.health != 0:
print(str(game.level))#for Testing
lbl = Label(root, text=lbBlue, font=SMALL_BUTTON_FONT)
lbl['text'] = 'level: ' + str(game.level)
lbl.place(x=35, y=15)
root.update()
print('Where is: ' + str(game.newDistance())+ ' and allowance is: ' + str(game.allowance))
#game.newDistance()
#count down
game.measureDistance()
if game.playerDistance >= game.lowerBound() and game.playerDistance <= game.upperBound():
game.level += 1
print('NEXT LEVEL')
else:
game.health -= 1
print('Ouch! You just lost a life your health is now: ' + str(game.health))
#u guessed ..... which is not in the range ..... ----> little diagram
game.allowance = int(game.allowance*0.90)
if game.allowance > 5:
game.allowance = int(game.allowance*0.90)
许多人将update
函数与mainloop
函数混淆。这两个函数之间的区别在于mainloop
函数阻塞,这意味着它不允许代码在调用后继续运行 - 通过在函数内部运行无限循环。但是update
函数只运行显示所有内容所需的次数,然后结束并继续执行代码。
答案 1 :(得分:0)
也许你应该尝试在 lbl 的定义下做 lbl.pack()
。通常有帮助