【发布时间】:2019-04-06 19:06:26
【问题描述】:
所以,我在制作带有透明图像的菜单按钮时遇到了一些问题。我以前使用透明图像作为按钮,删除背景没有问题。但是,在创建菜单按钮时,我似乎无法使图像透明。
使用此代码,我可以使用具有透明背景(例如圆形)的图像制作普通按钮,并且可以删除默认的彩色按钮背景:
button = tk.Button(self, compound = tk.TOP, borderwidth = 0, image = photo, text="some text", command = lambda: somemethod())
我尝试使用以下代码在菜单按钮上复制它:
style = ttk.Style()
style.configure("test.TButton", borderwidth = 0)
self.mb = ttk.Menubutton(self, text = "Menu", style = "test.TButton", image = photo)
但是我无法摆脱默认按钮背景,谁能帮我实现这个?
如果不清楚,我的目标是让菜单按钮使用没有背景的图像而不是文本,如果有更好的方法可以做到这一点,如果有人能告诉我,我将不胜感激。
需要明确的是,我的问题是 ttk Menubuttons,而不是常规的 tk 按钮。
另外,如果这很重要,我正在使用 Pillow 进行图像处理并使用 PNG 文件。
这是该问题的最小代码:
""" os imports """
import os
""" tkinter imports """
import tkinter as tk
from tkinter import ttk
""" pillow imports """
from PIL import Image, ImageTk
class MainView(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
home_path = os.path.normpath("Java.png")
self.home_icon = ImageTk.PhotoImage(Image.open(home_path))
style = ttk.Style()
style.configure("test.TButton", borderwidth = 0, compound = tk.TOP)
self.mb = ttk.Menubutton(parent, text = "Menu", style = "test.TButton", image = self.home_icon)
self.mb.grid(row = 0, column = 0, sticky = tk.N + tk.W)
button = tk.Button(parent, compound = tk.TOP, borderwidth = 0, image = self.home_icon, text="test", command = lambda: test()).grid(row = 1, column = 0, sticky = tk.N + tk.W)
def test(self):
pass
if __name__ == "__main__":
root = tk.Tk()
""" change aspect ratio of the program """
sizex = 1280
sizey = 720
posx = 0
posy = 0
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
main = MainView(root)
root.mainloop()
【问题讨论】:
-
请edit您的问题并添加更多代码——最好是minimal reproducible example。
ttk.Menubuttons 始终与tkinter.Menu小部件结合使用。 -
这是整个代码,除了grid/pack/place。按钮和图像为我显示,但不像我希望的那样透明。我没有费心为它编写任何进一步的代码,因为它当前没有按我的意愿显示。图像正确显示不需要 tkinter.Menu。
-
您的代码没有显示
self在ttk.Menubutton(self, ...)调用中的内容。此外,图像类型很重要……PNG格式图像有不同的“风格”。请在您的问题中添加指向图像文件的链接,以及足够的代码来重现问题。 -
我添加了一个最小示例和图片链接,您应该能够看到按钮和菜单按钮之间的并排区别
-
相关问题stackoverflow.com/questions/44331618/… 在这种情况下很有用。