简体   繁体   中英

Change text of a specific tkinter Label using function with arguments

I'm trying to reference a specific tkinter Label in a function based on an argument input. I've tried many things, and found some topics on exec and eval and variable variables, but I want to steer away from bad practices (I don't know how to achieve it through those methods anyway). I feel like I'm missing something extremely basic, but I can't wrap my head around it.

Below is a simplified code of my function:

    def myFunction(input_num):
        while ArbitraryVariableName == False:
            # Do stuff in while loop

        if input_num== "1":
            self.lbl1["text"] = "New Value 1"
        elif input_num == "2":
            self.lbl2["text"] = "New Value 2"
        elif input_num== "3":
            self.lbl3["text"] = "New Value 3"
        elif input_num== "4":
            self.lbl4["text"] = "New Value 4"
        elif input_num== "5":
            self.lbl5["text"] = "New Value 5"

        # And so forth for 20+ more elif statements

You will notice that the input_num directly relates to the specific tkinter Label name of " lbl + input_num ". If it helps, below is the code for one of two of the labels (they all follow a similar pattern):

    self.lbl1 = Label(topframe, text="Old Value Test 1")
    self.lbl1 .grid(column=1, row=1)

    self.lbl2 = Label(topframe, text="Old Value Test 2")
    self.lbl2 .grid(column=1, row=2)

    # And so forth

Is there a cleaner and less-repetitive way to do this?

You say that you don't want to have to use the eval function, so you could instead use a label list, which makes your code rather a lot shorter:

import tkinter as tk

class example:
    def __init__(self, master):
        self.master = master

        self.lbl1 = tk.Label(self.master, text="Old Value Test 1")
        self.lbl1.grid(column=0, row=0)

        self.lbl2 = tk.Label(self.master, text="Old Value Test 2")
        self.lbl2.grid(column=0, row=1)

        self.lbls = [self.lbl1, self.lbl2]

        self.myfunction(1)
        self.myfunction(2)

    def myfunction(self, input_num):
        self.lbls[input_num - 1]["text"] = f"New Value {input_num}"


def main():
    root = tk.Tk()
    example_win = example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

With this code I did assume you had an integer from the input_num variable, instead of the string you showed in your example.

If you aren't using Python 3 you can't take advantage of the f-string .

Hope this helps,

James

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM