Как стилизовать и настроить панель меню tkinter / guizero?

Я работаю с Tkinter и guizero и пытаюсь стилизовать строку меню. Я использую Python 3.8.2

То, что я пытаюсь изменить

  1. Удалите границу / 3D-эффект в строке меню и параметрах.

  2. Удалите прокладку верхней панели меню (небольшое пространство сверху и слева).

  3. Активный выбор цвета как для верхнего уровня / строки меню, так и для параметров.

from guizero import App, MenuBar

def file_function():
    print("File option")

def about_function():
    print("about option")

app = App(title="My app", height=300, width=500,bg='white')
menubar = MenuBar(app,
                    toplevel=["File", "About"],
                    options=[
                        [ ["New", file_function], ["Save", file_function]],
                        [ ["Report Bug", about_function], ["About", about_function] ]
                    ])

menubar.bg=(111, 77, 124)

# none of the styling below works and this is what I've tried
menubar.border=0
menubar.toplevel.border=False
menubar.options.border=0
menubar.toplevel.options.bg='gray'
menubar.toplevel.focus.bg='yellow'
menubar.toplevel.focus.fg='yellow'
menubar.toplevel.options.border=False
app.display()

Изображение:

введите описание изображения здесь

Обновить

В настоящее время меню не предназначено для того, чтобы хорошо выглядеть, странные цвета предназначены для того, чтобы увидеть, что работает, а что нет. Я могу использовать виджет Guizero и все их функции.

Текущие проблемы

  1. Невозможно удалить трехмерный / возможный эффект заполнения в меню и подменю, когда выбран элемент

Я пробовал установить границу на 0 и высоту выделения на 0

Обновленный код

from guizero import *
from tkinter import *

app=App(title='Test',bg=(53, 60, 81))
root = app.tk

def hello():
    print ("hello!")


#creates menubar
menubar = Menu(root,relief=FLAT,bd=0)




# Sets menubar background color and active select but does not remove 3d  effect/padding
menubar.config(bg = "GREEN",fg='white',activebackground='red',activeforeground='pink',relief=FLAT)


# First item on menubar and creates sub options
filemenu = Menu(menubar, tearoff=0,relief=FLAT, font=("Verdana", 12),activebackground='red')
filemenu.config(bg = "GREEN") 
filemenu.add_command(label="New (Ctrl + N)", command=hello)
filemenu.add_command(label="Save(Ctrl + S)", command=hello)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)



# Adds to menubar and creates sub options
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Cut", command=hello)
editmenu.add_command(label="Copy", command=hello)
editmenu.add_command(label="Paste", command=hello)
menubar.add_cascade(label="Edit", menu=editmenu)

helpmenu = Menu(menubar, tearoff=0,bg='green',fg='blue')

helpmenu.add_command(label="Report bug", command=hello)
helpmenu.add_command(label="About", command=hello)
menubar.add_cascade(label="Help", menu=helpmenu)

helpmenu.activebackground='red'



root.config(menu=menubar)
app.display()

person PurpleLlama    schedule 26.06.2020    source источник
comment
Что вы имеете в виду под работой с guizero И tkinter? Вы не можете смешивать GUI-Toolkits.   -  person Atlas435    schedule 30.06.2020
comment
Их можно комбинировать даже на сайте Guizero. (lawie.github.io/guizero/usingtk)   -  person PurpleLlama    schedule 30.06.2020
comment
Мне нужно извиниться: lawie.github.io/guizero/usingtk   -  person Atlas435    schedule 30.06.2020
comment
Можете ли вы предоставить гифку или изображение, чтобы лучше понять?   -  person Saad    schedule 30.06.2020
comment
Похоже, что guizero просто использует tkinter. Почему бы просто не написать все в tkinter?   -  person Mike - SMT    schedule 01.07.2020
comment
Я стараюсь, чтобы код был красивым и чистым, чтобы люди могли добавлять к нему, плюс guizero намного легче читать, и в целом документация в целом в основном хороша.   -  person PurpleLlama    schedule 01.07.2020
comment
пример (krita.org/wp-content/uploads/2019/ 03 / plugin-selection.png)   -  person PurpleLlama    schedule 01.07.2020
comment
Кажется, что guizero - это пакет, унаследованный от tkinter, думаю, у вас не получилось. Вам нужно создать меню самостоятельно.   -  person jizhihaoSAMA    schedule 01.07.2020
comment
@jizhihaoSAMA Я думаю то же самое. Поскольку tkinter использует стиль операционной системы, например, для Windows [vista, XP, default ..].   -  person Atlas435    schedule 01.07.2020
comment
В их документации, как говорится, вы можете получить доступ к внутреннему объекту, используя синтаксис ‹object_name› .tk. Итак, если это возможно в Tkinter, то это должно быть возможно и с guizero. К сожалению, у меня нет доступа к машине с Windows, поэтому я не могу найти решение.   -  person Saad    schedule 01.07.2020
comment
Я попытался перевести обычное tk-меню в формат guizero, изменив цель окна на app, изменив меню на строку меню и заменив основной цикл на app.display (). Добавление .tk, похоже, не работает, когда дело доходит до строки меню. Я использовал его для других элементов, таких как кнопки размещения и стилизации, и тому подобное. Кстати, я использую последнюю версию Ubuntu.   -  person PurpleLlama    schedule 01.07.2020
comment
Обычное меню можно добавить, используя app.tk как root   -  person Saad    schedule 01.07.2020
comment
хорошо, спасибо, Саад. Мне удалось это сделать, выполнив from tkinter import * from guizero import App app = App () root = app.tk   -  person PurpleLlama    schedule 01.07.2020
comment
Вы все еще ищете ответ или нашли его? Если вы нашли ответ, вы можете ответить на свой вопрос и принять его, чтобы вопрос был помечен как отвеченный.   -  person Saad    schedule 02.07.2020
comment
Я могу сделать только часть этого. Я могу удалить границу строки меню и отступ сверху. Я также могу изменить фон опций, но по-прежнему иметь часть 3D-эффекта в подменю. Я по-прежнему не могу изменить активный цвет при наведении курсора на элемент строки меню и его подменю.   -  person PurpleLlama    schedule 02.07.2020
comment
Теперь мне просто нужно удалить эффект 3D в выбранном меню и подменю.   -  person PurpleLlama    schedule 03.07.2020


Ответы (1)


Я разбил следующий код. Сначала вам нужно импортировать tkinter, иначе возникнет ошибка.

from tkinter import * 
from guizero import *


#background can be set rgb values,color name, and hex values
# width and height set the defualt startup window size
app=App(title='Test',bg=(53, 60, 81),width=500,height=500)

#sets min and max size of window
app.tk.minsize(width=250,height=250)
app.tk.maxsize(width=550,height=550)

root = app.tk


#Basic test function
def hello():
    print ("hello!")
    
    
        
    
#creates the menubar and sets the location to root window
menubar = Menu(root,relief=FLAT,bd=0)


'''
bg sets the menubar background color
fg sets the text color
activebackground sets the selected item background
activeforeground set the selected item text color
active borderwidth removes the 3d effect/border around item
font sets the font type and size
Defualt text,background and other things can be set with variables

'''

menubar.config(bg = "GREEN",fg='white',activebackground='red',activeforeground='purple',activeborderwidth=0,font=("Verdana", 12))


# create a pulldown menu, and add it to the menu bar
# background,foreground and bother border and active border width needs to be set to remove any 3d border effect
filemenu = Menu(menubar, tearoff=0,relief='flat', bd=0,activebackground='red',activeborderwidth=0,font=("Verdana", 12))
filemenu.config(bg = "GREEN") 
filemenu.add_command(label="New", command=hello)
filemenu.add_command(label="Save", command=hello)
#add line between drop down menu items
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
# sets the top level menu list name
menubar.add_cascade(label="File", menu=filemenu)





# create a pulldown menu, and add it to the menu bar
#example of no styling added to the sub menu
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Cut", command=hello)
editmenu.add_command(label="Copy", command=hello)
editmenu.add_command(label="Paste", command=hello)
# sets the top level menu list name
menubar.add_cascade(label="Edit", menu=editmenu)

# create a pulldown menu, and add it to the menu bar
# show custom effects can be add to each sub menu 
helpmenu = Menu(menubar, tearoff=0,bg='orange')
helpmenu.add_command(label="Report bug", command=hello)
helpmenu.add_command(label="About", command=hello)
# sets the top level menu list name
menubar.add_cascade(label="Help", menu=helpmenu)




# example of guizero widget
box = Box(app,height=200,width=500)
box.set_border(thickness=2, color='green')
box.bg=(53, 60, 81)
box.text_color='white'
exampel_text = Text(box, text="Hello World")
Picture(box,"example.png")


# display the menu and other things
root.config(menu=menubar)
app.display()
person PurpleLlama    schedule 03.07.2020