gpt4 book ai didi

python - 在 Tkinter 中将图像添加到按钮

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:32 24 4
gpt4 key购买 nike

我正在尝试将图像添加到按钮,但在尝试执行当前代码时遇到了一些问题。它所显示的只是一个没有文字的图像。我什至看不到按钮。有什么方法可以修复我当前的代码吗?

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()

最佳答案

您需要在窗口中打包(或网格)您的按钮,您可以这样做:

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()

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

button_qwer = tk.Button(root, image=imagetest, text="asdfasdf", compound="top", command=print_hello) 

compound 选项有bottom, center, left, none, ,或顶部

关于python - 在 Tkinter 中将图像添加到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52250213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com