[这是我的第一篇文章,所以请原谅我。我正在尝试制作骰子滚动游戏的GUI(2 x六面)。随机滚动的逻辑可以很好地用于控制台。同样在控制台中,我看到模具编号正在映射到正确的图像文件,但是在超出初始启动卷的每个卷上,我都无法将tkinter标签图像更改为新的对应图像。
在启动时,它会正确显示两个模具图像,但是当我单击“滚动”按钮时,来自第一个辊的两个图像都消失了,并且不显示新的辊图像。它只是使第一张滚动图像先前占用的空间空白。
仔细观察,我可以在屏幕上的正确位置看到正确的模具图像“闪光”,但是每次按“滚动”时,这些图像立即消失。
我无法附加我正在使用的六张图像以进行可能的模版轧制(缺乏信誉),但是重点是要演示从任何图像更改为其他图像的能力,因此可以随意尝试使用任何6种gif图像。
我在该站点上看到了类似的问题,但是当我尝试建议代码或建议代码组合时,我遇到了同样的问题。
我在win10pro上使用python 3.8.1。任何帮助,将不胜感激!这是我的代码:
from tkinter import *
import random
window = Tk()
window.title( 'Roller' )
window.resizable( 0, 0 )
def get_roll():
min=1
max=6
die1 = random.randint(min,max)
die2 = random.randint(min,max)
if die1 == die2:
print(die1,'+',die2,'=',die1+die2, '*** You rolled doubles ***')
else:
print(die1,'+',die2,'=',die1+die2)
return die1,die2
def get_image(index):
images = []
images.append('die_01_42158_sm.gif')
images.append('die_02_42159_sm.gif')
images.append('die_03_42160_sm.gif')
images.append('die_04_42161_sm.gif')
images.append('die_05_42162_sm.gif')
images.append('die_06_42164_sm.gif')
return images[index-1]
def do_roll():
global window
die1, die2 = get_roll()
imgfile1 = get_image(die1)
imgfile2 = get_image(die2)
print(imgfile1)
img1 = PhotoImage( file = imgfile1 )
#img1 = img1.subsample(20)
imgLbl1.configure( image = img1 )
#imgLbl1 = Label( window, image = img1 )
#imgLbl1.grid(row = 0, column = 0)
window.update_idletasks()
print(imgfile2)
img2 = PhotoImage( file = imgfile2 )
#img2 = img2.subsample(20)
imgLbl2.configure( image = img2 )
#imgLbl2 = Label( window, image = img2 )
#imgLbl2.grid(row = 0, column = 1)
window.update_idletasks()
die1, die2 = get_roll()
imgfile1 = get_image(die1)
imgfile2 = get_image(die2)
img1 = PhotoImage( file = imgfile1 )
#img1 = img1.subsample(20)
imgLbl1 = Label( window, image = img1 )
imgLbl1.grid( row = 0, column = 0 )
img2 = PhotoImage( file = imgfile2 )
#img2 = img2.subsample(20)
imgLbl2 = Label( window, image = img2 )
imgLbl2.grid( row = 0, column = 1 )
rollBtn = Button( window )
rollBtn.grid( row = 0, column = 2 )
rollBtn.configure( text = 'Roll' )
rollBtn.configure( command = do_roll )
quitBtn = Button( window )
quitBtn.grid( row = 0, column = 3 )
quitBtn.configure( text = 'Quit' )
quitBtn.configure( command = window.destroy )
#do_roll()
window.mainloop()
由于您使用了局部变量来保存图像,因此将在函数后对其进行垃圾回收。
您必须保留图像的引用:
def do_roll():
die1, die2 = get_roll()
imgfile1 = get_image(die1)
imgfile2 = get_image(die2)
print(imgfile1)
imgLbl1.image = PhotoImage( file = imgfile1 )
imgLbl1.configure( image = imgLbl1.image )
print(imgfile2)
imgLbl2.image = PhotoImage( file = imgfile2 )
imgLbl2.configure( image = imgLbl2.image )