【问题标题】:Adding an image to a button in Tkinter将图像添加到 Tkinter 中的按钮
【发布时间】:2019-02-14 10:34:54
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    你需要在窗口中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()
    

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

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

    compound 选项为 bottomcenterleftnonerighttop

    【讨论】:

    • 顺便问一下,在 Python 中真的有可能获得同时具有图像和文本的按钮吗?我最初打算使用一种同时显示图像和文本的方法,但至少我得到了显示图像的按钮。目前,我只显示了图像。
    • 是的,有可能,像这样:button_qwer = tk.Button(root, image=imagetest, text="asdfasdf", command=print_hello, compound="top")
    【解决方案2】:

    您已成功制作按钮,但未将其绘制到屏幕/界面上。使用packplacegrid

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

    你的完整代码可以是:

    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)
    button_qwer.pack()
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2023-01-01
      • 2021-04-06
      • 2020-08-24
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多