[英]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.