在Tkinter中将图像添加到按钮

Ron*_*ang 3 python tkinter python-3.x

我正在尝试将图像添加到按钮,但是当我尝试执行当前代码时遇到了一些问题。它显示的只是一张没有文字的图像。我什至都看不到按钮。有固定我当前代码的某种方法吗?

from tkinter import *
import tkinter as tk

root = tk.Tk()
root.geometry("960x600")

canvas = Canvas(root, width=500, height=500)
canvas.pack()

imagetest = PhotoImage(file="giftest.gif")
canvas.create_image(250, 250, image=imagetest)

button_qwer = Button(root, text="asdfasdf", image=imagetest)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

Reb*_*que 5

您需要pack(或grid)在窗口中的按钮,这是您可以执行的操作:

import tkinter as tk
from tkinter import PhotoImage

def print_hello():
    print('hello')

root = tk.Tk()
root.geometry("960x600")

imagetest = PhotoImage(file="giftest.gif")

button_qwer = tk.Button(root, text="asdfasdf", image=imagetest, command=print_hello)
button_qwer.pack()   # <-- don't forget to place the button in the window

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

您可以使用选项在按钮上同时显示文本和图像compound,如下所示:

button_qwer = tk.Button(root, image=imagetest, text="asdfasdf", compound="top", command=print_hello) 
Run Code Online (Sandbox Code Playgroud)

compound选项包括bottomcenterleftnoneright,或者top