Customtkinter optionmenu

3.1k Views Asked by At

I want to have a customtkinter option menu to let the user choose which line of a txt file they want to have for the speed typing test. I'm making a speed typing test in Tkinter namely. Now, I have it randomly chosen.

So what I've written in python:

def load_text():
    with open("filename.txt", "r") as f:
        lines = f.readlines()
        return random.choice(lines).strip()

def resetWritingLabels():    
    # Choosing one of the texts randomly with the choice function
    text = load_text()
    etc... 

What I've tried is something like this:

# this is the option menu to change the sentence during the start, so not when you've finished the test.

values = ["1", "2", "3"] 
optionbox = customtkinter.CTkOptionMenu(master=root,
                                            values=values,
                                            command=lesson_option)
optionbox.grid(row=0, column=0, columnspan=1, pady=10, padx=20, sticky="w")
optionbox.set("1") # I want it to be set to the default sentence: sentence of row 1 of the txt file.

lesson_option(choice):
lesson_number = int(choice) - 1
return lesson_number

def load_text():
    with open("filename.txt", "r") as f:
        lines = f.readlines()
        lesson_number = lesson_option()
        return lines[lesson_number].strip()

def resetWritingLabels():    
    # Choosing the sentence using the option menu 
    text = load_text()
    etc...

Unfortunately, I get a lot of errors like TypeError. I also tried it with optionbox.get(), but without good results unfortunately.

1

There are 1 best solutions below

0
VanN On

I think you declare the CtkOptionMenu not correctly. It should be:

optionbox_var = customtkinter.StringVar(value="1")
    optionbox = customtkinter.CTkOptionMenu(master=root,
                                            values=values,
                                            variable=optionbox_var,   
                                            command=lesson_option)
    optionbox.grid(row=0, column=0, columnspan=1, pady=10, padx=20, sticky="w")