首页 > 解决方案 > tkinter - 单击按钮时显示数组中的随机图像

问题描述

我想要一个标签在单击按钮时显示随机图像。

这是我的方法,但它不起作用。欢迎任何关于如何解决的想法。

from tkinter import *
import random
window = Tk()

filechoices = ["image1.png", "image2.png", "image3.png"]

filename = PhotoImage(file = random.choice[filechoices]) 

def press():    
    image = Label(window, image=filename).pack()

button1 = Button(window, text="click to see image", command = press)
button1.pack()

标签: python-3.xtkinter

解决方案


random.choice是一个函数,而不是一个列表。

它应该是:

filename = PhotoImage(file = random.choice(filechoices)) 

读取随机模块

random.choice(seq) 从非空序列 seq 返回一个随机元素。

另外,在您的代码中,您还没有使用mainloop()


推荐阅读