将图像添加到 Tkinter 中的按钮

编程入门 行业动态 更新时间:2024-10-26 21:35:45
本文介绍了将图像添加到 Tkinter 中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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 选项有 bottomcenterleftnonerighttop

compound options are bottom, center, left, none, right, or top

这篇关于将图像添加到 Tkinter 中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 08:13:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   图像   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!