If I understand your code, you are doing everything correctly syntactically. If the value is appearing blank on the screen, the only explanation is that commentEntryVar
is a local variable that is being garbage-collected after the widget is created but before the window appears.
If it is a local variable, when the function exits the variable will be destroyed and thus the default value will be thrown away. For example, this minimal program illustrates the effect you're seeing since it is using a local variable:
import Tkinter as tk
import ttk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
workoutParametersFrame = tk.Frame(self)
workoutParametersFrame.pack(fill="both", expand=True);
# start code from the question
commentEntryVar = tk.StringVar()
commentEntryVar.set("default text")
print "commentEntryVar"
print commentEntryVar.get()
commentEntryWidget = ttk.Entry(workoutParametersFrame,
textvariable=commentEntryVar)
commentEntryWidget.grid(row=6, column=1)
# end code from the question
if __name__ == "__main__":
root = tk.Tk()
app = Example(root)
app.pack(fill="both", expand=True)
app.mainloop()
The fix is to keep a reference to the StringVar so that it is not garbage collected. In this code we're using a class so we can store a reference in a class variable. If you are not using classes and objects you'll need to store it in a global variable.
For example, if you change commentEntryVar
to self.commentEntryVar
, the problem goes away because the object holds a persistent reference:
...
self.commentEntryVar = tk.StringVar()
...
commentEntryWidget = ttk.Entry(..., textvariable=self.commentEntryVar)
...