Domanda

I want to use config.ini's values as startup values for Tkinter Entry items. When the program is finished, I want to write the content of these Entry into the config.ini. I have 2 problems with the following code :

# create the Entry textboxes
e1 = Entry(f1); e1.grid(row=1,column=1,sticky=W)
e2 = Entry(f1); e2.grid(row=2,column=1,sticky=W)
e3 = Entry(f1); e3.grid(row=3,column=1,sticky=W)

# fill them with content from config.ini file
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')
e1.insert(0, config.get('Default','Param1'))
e2.insert(0, config.get('Default','Blah7'))
e3.insert(0, config.get('Default','Param3'))

tk.mainloop()

# save the Entry values to config.ini
config.set('Default', 'Param1', e1.get())
config.set('Default', 'Blah7', e2.get())
config.set('Default', 'Param3', e3.get())
config.write(open('config.ini','w'))
  • First problem : once the tk.mainloop() is finished, e1.get() doesn't work anymore!

  • Second problem : it's not so beautiful to have to repeat the same things 2 times in the code (once for reading, once for writing). Maybe there's a way to link the Entry with the config.ini parameters in a shorter way ?

È stato utile?

Soluzione

Program (and all widgets) exists as long as mainloop is working - not only in tkinter but also in wxpython, pygame, etc. When mainloop is finishing work it destroys all widgets and window. You have to save config before mainloop.

You can add button quit with assinged function which save config and than close program.

(not tested code)

def saveConfig():
    global config

    config.set('Default', 'Param1', e1.get())
    config.set('Default', 'Blah7', e2.get())
    config.set('Default', 'Param3', e3.get())
    config.write(open('config.ini','w'))

    root.quit()

Button(root, "QUIT", command=saveConfig)

Maybe you could also assing this function to closing event to save config when user use close button [X].

root.protocol("WM_DELETE_WINDOW", saveConfig)

Code reading config and code writing config are not identical. There is no shorter way.

You can only use lists and for loop to make load/save "nicer" :)

 entries = []
 options = []

 entries.append(Entry(f1)); entries[-1].grid(row=1,column=1,sticky=W)
 options.append("Param1")

 entries.append(Entry(f1)); entries[-1].grid(row=2,column=1,sticky=W)
 options.append("Blah7")

 entries.append(Entry(f1)); entries[-1].grid(row=3,column=1,sticky=W)
 options.append("Param3")

 # load

 import ConfigParser
 config = ConfigParser.ConfigParser()
 config.read('config.ini')

 for index, e in enumerate(entries):
     e.insert(0, config.get("Default", options[index]) )

 # save

 for index, e in enumerate(entries):
     config.set("Default", options[index], e.get())

 config.write(open('config.ini','w'))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top