Tkinter,按钮单击实验室中特定图片的if语句

2024-10-01 04:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用随机给出的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()


Tags: imageconfigifdef图片placepassgif
1条回答
网友
1楼 · 发布于 2024-10-01 04:45:10

我建议使用一个列表来保存图像,并使用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,所以我无法测试整个应用程序,所以可能有bug。在

相关问题 更多 >