简体   繁体   中英

Reading python ttk Styles from configuration file

Using python ttk and the ConfigParser leads me to the following issue.

I want to use a Configuration File to make Styles adaptable during usage for every user - not only the ones with access to the sources.

Using the ttk-styles inside my python script (Python 2.7) from hardcoded sections work like a charm

def LoadStyles(self):
  s=ttk.Style()

  if not os.path.exists("Styles.cfg"):
     s.configure('TFrame', background='white')
     s.configure('Dark.TFrame', background='#292929')
  else:
     config=ConfigParser.RawConfigParser()
     config.read("Styles.cfg")

     for section in config.sections():
        for (key, val) in config.items(section):
           try:
              s.configure(section, key="%s"%val)
           except:
              print("Error Parsing Styles Config File:  [%s].%s = %s"%(section, key, val))

Using the Configuration File (contents below) results in white backgrounds for all Frames, also the ones that are declared like

self.loginFrame=ttk.Frame(self, style='Dark.TFrame')

EDIT: they are not white but non-filled (default fill) .

The styling is both ways done before the widgets are loaded, either hardcoded or by config file.

I just don't get where i am stuck in here, manuals and SO Search just did not give me any answers on that one...

[TFrame]
background = "white"
[Dark.TFrame]
background = "#292929"

Any help is really appreciated.

Finally i got the solution:

The issue was that "key" was written as keyword into the style. eg {'key': '#292929'} This data could be read using

print(s.configure(section))

after the

s.configure(section, key="%s"%val)

Keyword unpacking was the clue: (Thanks a lot to SO )

for section in config.sections():
    for (key, val) in config.items(section):
        try:
            test={ "%s" % key : "%s" % val }
            s.configure(section, **test)
        except:
            print("Error Parsing Styles Config File:")
            print("   [%s].%s = %s"%(section, key, val))

Now also the Styles read from the Configuration File can be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM