Nitram
Nitram

Reputation: 1

Get the style object when only the style name is known

I started to use ttk Styles. I have now the problem, to find the style object if I only know the style name. I would like to read out properties from the style settings. This is not really a practical problem, I just want to understand.

This is what I expect:

import tkinter as tk
from tkinter import ttk

tk_win = tk.Tk()

l_geometry = '400x200+100+100'
tk_win.geometry(l_geometry)

style = ttk.Style()                                                                
style.configure('Style_name.TLabel',
                foreground='blue', 
                background="yellow")
label = ttk.Label(tk_win, text = 'Just a Test_Label', 
                  style = 'Style_name.TLabel')    
label.place(x=10, y=10)

print (style.lookup('Style_name.TLabel', 'background'))                               

tk_win.mainloop()

This is working fine. In this case it prints "yellow'.

Now I tried to use it in a function. Where my problem is now starting. This is the program code I used.

import tkinter as tk
from tkinter import ttk


def get_bg(inp_label):

    background = ''
    style_name = inp_label['style']    # Not the style object

    # style_name is only a string. 
    # ????.lookup('Style_name.TLabel', 'background')  

    return background

tk_win = tk.Tk()

l_geometry = '400x200+100+100'
tk_win.geometry(l_geometry)

style = ttk.Style()                                                                     
style.configure('Style_name.TLabel',
                foreground='blue',
                background="yellow")          

label = ttk.Label(tk_win, text = 'Just a Test_Label', 
                  style = 'Style_name.TLabel')    
label.place(x=10, y=10)

print (get_bg(label))                                           

tk_win.mainloop()

I have no clue how I can get the style object when I only know the style name. Without getting this link the attribute ['style'] in the label properties is for information only. I also know there are plenty of programming ways around. eg. Pass over the object additionally, or creating a dict{name: style} ... But to use it directly from the label would be the smartest way in my opinion.

I am using Ubuntu 22.04 and Python 3.10.12

I surfed the internet now for 2 days, but without success. I found a function called 'nametowidget'. This is doing what I am searching for, but I can' find a similar function in regards of styles.

Upvotes: 0

Views: 108

Answers (0)

Related Questions