Home > front end >  How to change multiple labels in multiple classes with a tkinter dropdown menu
How to change multiple labels in multiple classes with a tkinter dropdown menu

Time:05-18

So, I want the user to be able to use my program in English. They should be able to switch to their language via a dropdown-menu. My program has only four pages and a few labels on each, translating them with a toolkit would be unnecessary.

This is, what I got this so far:

    # Language Settings
    def display_selected(choice):
        choice = variable.get()
        if choice == "Deutsch":
            languagelabel.config(text=str('Sprache:'))
            Page1(self).label_search.config(text=str('Suche'))

        else:
            languagelabel.config(text=str('Language:'))
            Page1(self).label_search.config(text=str('search'))


    # Dropdown Menu for Languages
    languages = ['Deutsch', 'English']
    variable = StringVar()
    variable.set(languages[0])
    dropdown = OptionMenu(self, variable, *languages, command=display_selected)

The languagelabel in the same class changes, but the search_label in the class 'Page1' doesn't. Nothing happens, am I missing something?

I'm a bit of a novice, so any guidance and/or other solutions would be appreciated!

CodePudding user response:

One option I can think of would be using StringVar()s to store the labels that need translation for each language option, and the assigning those variables to each label's textvariable parameter

# EXAMPLE
lang_label_var = tk.StringVar()
label_search = tk.Label(
    textvariable = lang_label_var
    # whatever other attributes
)
search_label_var = tk.StringVar()
languagelabel = tk.Label(
    textvariable = search_label_var
    # whatever other attributes
)

You should be able to set() these variables to whichever word is appropriate for English or German with similar logic following choice = variable.get(). The label text for each item should update automatically when the variable assigned to textvariable is set.

if choice == 'Deutsch':
    lang_label_var.set('Sprache:')
    search_label_var.set('Suche')
elif choice == 'English':
    lang_label_var.set('Language:')
    search_label_var.set('Search')
  • Related