[英]How can I put image on Button in python tkinter?
This is my code in Tkinter. 这是我在Tkinter的代码。 I tried to show buttons with the image when I select the grid size in tkinter UI.
当我在tkinter UI中选择网格大小时,我试图用图像显示按钮。 My problem is that when I go to put an image inside a button, it does not display it.
我的问题是,当我将图像放在按钮内时,它不显示它。 List grid2 already have images with using the shuffle method.
列表grid2已经有使用shuffle方法的图像。 Any help is appreciated.
任何帮助表示赞赏。
import tkinter
import tkinter.ttk
import random
def startButton():
global my_list, roundNum, tmp_list, startTime
grid_size = combobox1.get()[0]
roundNum = combobox2.get()[0]
gridActorList(my_list)
imageUpdate()
startTime=time.time()
def imageUpdate():
global grid_size
t = []
if grid_size == 2:
photo_1 = tkinter.PhotoImage(file="picture/"+grid2[0]+".png")
photo_2 = tkinter.PhotoImage(file="picture/"+grid2[1]+".png")
photo_3 = tkinter.PhotoImage(file="picture/"+grid2[2]+".png")
photo_4 = tkinter.PhotoImage(file="picture/"+grid2[3]+".png")
for k in range(1,5):
t.append(tkinter.Button(window, image=photo_+str(k)))
for i in range(0,4):
t[i].pack()
window = tkinter.Tk()
window.title('Finding different picture!')
window.geometry('500x400')
#combobox
values1=[str(i)+"x"+str(i) for i in range(2,6)] #grid size
values2=[str(j)+"times" for j in range(1,10,2)] #play time size
combobox1=tkinter.ttk.Combobox(window, height=5, width=15, values=values1,
justify='center', takefocus=True )
combobox2=tkinter.ttk.Combobox(window, height=5, width=15, values=values2,
justify='center', takefocus=True )
combobox1.set("select size")
combobox2.set("select times")
combobox1.place(x=15, y=15)
combobox2.place(x=155, y=15)
#startButton
startBtn = tkinter.Button(window, text='start', command=startButton)
startBtn.place(x=300, y=15)
#variables
my_list = []
roundNnum = 0
window.mainloop()
I've tried to minimize the code. 我试图最小化代码。 If there are more codes required, I'll edit it.
如果需要更多代码,我将对其进行编辑。
Your code does not run. 您的代码无法运行。 This makes it hard to debug.
这使得调试变得困难。 But I can see that you're not saving references to the images you put in the buttons.
但是我可以看到你没有保存对按钮中放置的图像的引用。
As the images are created inside a function they will be garbage collected when the function exits. 当图像在函数内部创建时,它们将在函数退出时被垃圾收集。 Fix this by saving a reference to the image with the button widget.
通过使用按钮小部件保存对图像的引用来解决此问题。 Examine the example below:
检查以下示例:
import tkinter as tk
def create_button():
photo = tk.PhotoImage(file="images/gilliam.png")
image_button = tk.Button(window, image=photo)
image_button.image = photo # Save a reference to the image
image_button.pack()
window = tk.Tk()
create_button()
window.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.