Python 3.x - using text string as variable name

后端 未结 3 701
难免孤独
难免孤独 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:04

    Create lists of objects rather than individual attributes for each object. For example,

    import tkinter as tk
    from tkinter import *
    
    class Window:
        def __init__(self):
            self.settings_window()
    
        def Settings_Window(self):
            self.settings_window = tk.Tk()
            self.settings_window.minsize(200,200)
    
            self.entries = [
                Entry(self.settings_window), 
                Entry(self.settings_window)
            ]
    
            for e in self.entries:
                e.pack()
    
            self.labelinputs = [
                StringVar(),
                StringVar()
            ]
    
            self.labels = [
                Label(self.settings_window, textvariable=label, bg='yellow')
                for label in self.labelinputs
            ]
    
            for l in self.labels:
                l.pack(expand='yes', fill='x')
    
            self.buttons = [
                Button(self.settings_window,text='SETUP1',command=lambda: self.return_label(0))
                Button(self.settings_window,text='SETUP2',command=lambda: self.return_label(1))
            ]
    
            for b in self.buttons:
                b.pack()
    
            self.settings_window.mainloop()
    
        def return_label(self,number):
            entry_field_value = self.entry.get()
            self.labelsinput[number].set(entry_field_value)
    
    window=WINDOW()
    

提交回复
热议问题