Python 3.x - using text string as variable name

后端 未结 3 695
难免孤独
难免孤独 2021-01-28 19:32

I\'m trying to avoid to multiply functions in code by using

def Return_Label(self,number)  

with a parameter.

Any Idea how to use st

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-28 20:23

    I prefer a list approach to managing multiple entry fields and updating values. By using list you can use the index value to manage the labels as well :D.

    See the below example of how you can use list to deal with all the values and updates.

    import tkinter as tk
    from tkinter import *
    
    class Window(tk.Tk):
        def __init__(self):
            super().__init__()
            self.minsize(200, 200)
            self.entry_list = []
            self.label_list = []
            entry_count = 2
    
            for i in range(entry_count):
                self.entry_list.append(Entry(self))
                self.entry_list[i].pack()
    
            for i in range(entry_count):
                self.label_list.append(Label(self,bg='yellow'))
                self.label_list[i].pack(expand='yes', fill='x')
    
            Button(self, text='SETUP', command=self.Return_Label).pack()
    
        def Return_Label(self):
            for ndex, lbl in enumerate(self.label_list):
                lbl.config(text=self.entry_list[ndex].get())
    
    if __name__ == '__main__':
        Window().mainloop()
    

提交回复
热议问题