我正在尝试随机提供4张照片(标签中一次只有一张)。下面有4个按钮作为答案选项。按钮始终保持不变,只是在回答正确的问题后图片会随机变化。所以当有图片时,按下右键后图片应该变成另一张图片。如果按错了按钮,则不会发生任何事情。
到目前为止,问题在于提到目前以正确的方式看到的图片。
现在,我在正确回答之后尝试将图片更改为下一张图片,因为我不知道如何插入随机更改。
感谢您的帮助!
from tkinter import *
from random import randint
Fenster = Tk()
Fenster.title('training')
Fenster.geometry('1024x720')
# images
img110 = PhotoImage(file='1.gif')
img120 = PhotoImage(file='2.gif')
img130 = PhotoImage(file='3.gif')
img140 = PhotoImage(file='4.gif')
# Label image
bild=randint(1,4)
if bild==1:
labelbild = Label(image=img110)
elif bild==2:
labelbild = Label(image=img120)
elif bild==3:
labelbild = Label(image=img130)
elif bild==4:
labelbild = Label(image=img140)
labelbild.place(x=350, y=150)
#actions
def button110Click():
if bild==1:
labelbild.config(image=img120)
else:
pass
def button120Click():
if bild==2:
labelbild.config(image=img130)
else:
pass
def button130lick():
if bild==3:
labelbild.config(image=img140)
else:
pass
def button140Click():
if bild==4:
labelbild.config(image=img110)
else:
pass
# Buttons
button110 = Button(master=Fenster, text='108', bg='#D5E88F', command=button110Click)
button110.place(x=350, y=420, width=40, height=40)
button120 = Button(master=Fenster, text='120', bg='#FFCFC9', command=button120Click)
button120.place(x=440, y=420, width=40, height=40)
button130 = Button(master=Fenster, text='128.57', bg='#FBD975', command=button130Click)
button130.place(x=530, y=420, width=40, height=40)
button140 = Button(master=Fenster, text='135', bg='#FBD975', command=button140Click)
button140.place(x=620, y=420, width=40, height=40)
Fenster.mainloop()
答案 0 :(得分:0)
我建议使用列表来保存图片,并使用bild
作为此列表的索引。
from random import randint
import tkinter
# number of images
N = 4
# Use a Python 'list comprehension' to build a list of images
images = [ PhotoImage(file='%d.gif') % i for i in range(1,N+1)]
bild = 0
def new_image():
# Select and display the an image
global bild
bild = randint(0,N-1)
labelbild = label(images[bild])
labelbild.place(x=350, y=150)
new_image()
# actions
# (I bet there's a parametric way to do this using one function, but I don't know tkinter)
def button110Click():
if bild == 0:
new_image()
def button120Click():
if bild == 1:
new_image()
def button130Click():
if bild == 2:
new_image()
def button140Click():
if bild == 3:
new_image()
# The rest is the same as in the OP.
由于我没有tkinter,我无法测试完整的应用程序,因此可能存在错误。