When I run the below code sometimes the entry has the value I want it to have by default and sometimes it doesn't. each time I run it everything is pretty much the same but the results are different! Someone please help me find what is going on!
Here is my code:
from settings import Settings
from tkinter import *
root = Tk()
settings = Settings(root, "Z:\my files\projects\programing\python\courseAssist\Courses")
parent_directory = Entry(
root,
width=60,
textvariable=settings.parent_directory_var,
text="Please enter the root directory for all the files and directories to be saved and created in."
)
parent_directory.pack()
mainloop()
And here is the code in the settings file:
from tkinter import *
class Settings:
def __init__(self, root, parent_directory):
self.parent_directory_var = StringVar(root, value=parent_directory)
At least part of the problem is the fact that you use textvariable=...
followed by text=...
. The Entry
widget has no text
attribute; text
in this context is just a shorthand for textvariable
. In tkinter, if you specify the same option twice, the last one is used. Thus, your code is the same as Entry(...,textvariable="Please enter the root...", ...)
.
If your goal with text="Please enter the root...
" is to create a prompt, you will need to use a Label
widget in addition to the Entry
widget. If your goal is to insert that string as the value of the Entry
widget, you can call the set
method of the variable (eg: settings.parent_directory_var.set("Please enter the root...")
).
Also, are you aware that a backslash in a normal string is an escape character? You need to either use a raw string, double backslashes, or forward slashes (yes, forward slashes are valid in windows paths)
For example, all three of these are equivalent:
"Z:\\my files\\projects\\programing\\python\\courseAssist\\Courses"
"Z:/my files/projects/programing/python/courseAssist/Courses"
r"Z:\my files\projects\programing\python\courseAssist\Courses"