【发布时间】:2015-01-12 12:36:40
【问题描述】:
我正在尝试制作骰子,因此每张图片都是骰子面的图片,我希望它使用按钮随机选择其中一张图片,然后将其打印在屏幕上的图片替换为另一张随机图片当按钮被点击时
因此,当我运行该模块时,它会弹出 6 个随机图像之一,但是一旦我单击“滚动”按钮,它就不会将图像更改为另一个随机图像,而是使图像消失。我希望变量“myimg”根据“数字”变量更改其值,然后使用按钮将打印在 tkinter 窗口上的图像替换为已知的“myimg”值。
import random
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Dice")
window.geometry("400x400")
window.configure(background='white')
count= 1
while count == 1:
number = random.randint(1,6)
if number == 1:
myimg = "1.jpg"
count = 0
elif number == 2:
myimg = "2.jpg"
count = 0
elif number == 3:
myimg = "3.jpg"
count = 0
elif number == 4:
myimg = "4.jpg"
count = 0
elif number == 5:
myimg = "5.jpg"
count = 0
elif number == 6:
myimg = "6.jpg"
count = 0
def update_the_picture():
updated_picture = ImageTk.PhotoImage(Image.open(myimg))
w.configure(image = updated_picture)
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expect an image object.
img = ImageTk.PhotoImage(Image.open(myimg))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
w = tk.Label(window, image = img)
b = tk.Button(window, text="Role Dice", command = update_the_picture)
#The Pack geometry manager packs widgets in rows or columns.
w.pack(side = "bottom", fill = "both", expand = "yes")
b.pack()
count= 1
#Start the GUI
window.mainloop()
【问题讨论】: