【问题标题】:tkinter - display random image from array on button clicktkinter - 单击按钮时显示数组中的随机图像
【发布时间】:2020-03-29 11:12:20
【问题描述】:

我希望标签在单击按钮时显示随机图像。

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

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.x tkinter


【解决方案1】:

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

应该是:

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

阅读random module

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

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

【讨论】:

  • 基本上,我用 [] 括号代替 ()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 2016-03-14
  • 2021-08-24
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多