问题描述
限时送ChatGPT账号..我正在尝试向按钮添加图像,但在尝试执行当前代码时遇到了一些问题.它显示的只是一个没有文字的图像.我什至看不到按钮.有什么办法可以修复我当前的代码吗?
I am trying to add an image to a button, but I have got some issues when I try to execute the current code. All it shows is an image with no words. I can't even see the button either. Is there some way of fixing my current code?
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()
推荐答案
你需要在窗口中pack
(或grid
)你的按钮,这是你可以的方法做:
You need to pack
(or grid
) your button in the window, here is how you could do:
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
选项在按钮上同时显示文本和图像,如下所示:
You can have both text and image displayed on your button, using the compound
option, like this:
button_qwer = tk.Button(root, image=imagetest, text="asdfasdf", compound="top", command=print_hello)
compound
选项有 bottom
、center
、left
、none
、right
或 top
compound
options are bottom
, center
, left
, none
, right
, or top
这篇关于将图像添加到 Tkinter 中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论