簡體   English   中英

您可以將圖像顯示為tkinter中的按鈕而不是按鈕上的圖像嗎?

[英]Can you get images to display as button in tkinter rather than on the button?

我正在使用TKinter為我正在做的項目構建GUI。 我想知道是否可以讓TKinter顯示圖像來代替沒有邊框的按鈕,而只顯示要單擊的圖像。 而不是顯示按鈕頂部 ,而按鈕邊框仍然在那里,我知道可以使用以下代碼實現:

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

這將導致本教程中顯示的內容

我希望我能清楚地解釋自己; 提前致謝!

如果您想要一個沒有邊框的按鈕,可以將邊框寬度設置為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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM