如何知道 ttk 小部件的所有样式选项 [英] how to know all style options of a ttk widget

查看:54
本文介绍了如何知道 ttk 小部件的所有样式选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题差点让我抓狂.我是一个新手,对 tck/tk 一无所知.我在网上仔细搜索过,但没有找到好的解决方案.

This problem nearly makes me craze. I am a new beginner and without knowledge of tck/tk. I have done carefully search on the internet but haven't found a good solution.

例如,我使用

import tkinter as tk
from tkinter import ttk
newBT = ttk.LabelFrame(width=100, height=100)

然后我需要设置框架样式.tk.LabelFrame 有前景.但是,我没有在 NMTtck/tk 参考.那我就得猜了,像下面

Then I need to set the frame style. There is foreground for tk.LabelFrame. However, I didn't find such style option for ttk.LabelFrame on NMT and tck/tk reference. Then I have to guess, like following

s = ttk.Style()
s.configure('TLabelframe', foreground='red')

但这不起作用,正确的事情

s.configure('TLabelframe.Label', foreground='red')

所以,我的问题是,如何找出 ttk 小部件具有的所有样式选项.有没有像

So, my question is, how can I find out all the style options a ttk widget has. Is there some function like

s.getAllOptions('TLabelframe')

然后输出类似于

['background', 'foreground', 'padding', 'border', ...]

谢谢!

推荐答案

我发现你的问题很有趣,因为我曾经问过自己同样的问题,但直到现在才找到时间来解决它.我编写了一个名为 stylename_elements_options(stylename) 的函数来做到这一点.在这里分享.希望它可以使您受益(尽管晚了 6 个月)和任何 tkinter 用户提出同样的问题.

I found your question interesting as I had asked myself the same question but have not found time to address it until now. I have written a function called stylename_elements_options(stylename) to do just this. Sharing it here. Hope it can benefit you (although it is 6 months late) and any tkinter users asking the same question.

脚本:

import tkinter as tk
import tkinter.ttk as ttk

def stylename_elements_options(stylename):
    '''Function to expose the options of every element associated to a widget
       stylename.'''
    try:
        # Get widget elements
        style = ttk.Style()
        layout = str(style.layout(stylename))
        print('Stylename = {}'.format(stylename))
        print('Layout    = {}'.format(layout))
        elements=[]
        for n, x in enumerate(layout):
            if x=='(':
                element=""
                for y in layout[n+2:]:
                    if y != ',':
                        element=element+str(y)
                    else:
                        elements.append(element[:-1])
                        break
        print('\nElement(s) = {}\n'.format(elements))

        # Get options of widget elements
        for element in elements:
            print('{0:30} options: {1}'.format(
                element, style.element_options(element)))

    except tk.TclError:
        print('_tkinter.TclError: "{0}" in function'
              'widget_elements_options({0}) is not a regonised stylename.'
              .format(stylename))

stylename_elements_options('my.Vertical.TScrollbar')

这篇关于如何知道 ttk 小部件的所有样式选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆