【问题标题】:Can you get images to display as button in tkinter rather than on the button?你能让图像在 tkinter 中显示为按钮而不是按钮吗?
【发布时间】:2019-05-28 01:17:27
【问题描述】:

我正在使用 TKinter 为我正在做的项目构建 GUI。我想知道是否有可能让 TKinter 显示一个图像代替一个没有边框的按钮,只有要单击的图像; 而不是在按钮的顶部显示,按钮边框仍然在那里,我知道可以使用如下代码实现:

photo=PhotoImage(file="add.png")
b = Button(master,image=photo, command=callback, height=50, width=150)
b.pack()

这将导致类似于this tutorial 中显示的内容

我希望我清楚地解释了自己;提前致谢!

【问题讨论】:

    标签: python image button tkinter


    【解决方案1】:

    如果您想要一个没有边框的按钮,您可以将边框宽度设置为 0:bd=0。当你按下它时,图像仍然会向右下方移动一个像素左右。

    这还不够好,您可以使用标签创建自定义按钮并将鼠标按下和释放绑定到该标签。

    from tkinter import *
    
    root = Tk()
    
    def callback_function():
        print('Button')
    
    # Image button without border
    button_img = PhotoImage(file='image_button.png')
    b = Button(root, image=button_img, bd=0, command=callback_function)
    b.pack(pady=10)
    
    # Custom button using a label
    up_img = PhotoImage(file='image_button_up.png')
    dn_img = PhotoImage(file='image_button_dn.png')
    e = Label(root, image=up_img, bd=0)
    e.pack(pady=10)
    
    # Functions for switching images when button is pressed/released
    def press(event):
        e.config(image=dn_img)
    
    def release(event):
        e.config(image=up_img)
        callback_function() # Invoke callback function on release
    
    # Bindings for mouse on label
    e.bind('<ButtonPress-1>', press)
    e.bind('<ButtonRelease-1>', release)
    
    root.mainloop()
    

    【讨论】:

    • 添加了两种实现的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    相关资源
    最近更新 更多