Please help to make the code smaller - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code Review (https://python-forum.io/forum-46.html) +--- Thread: Please help to make the code smaller (/thread-32631.html) |
Please help to make the code smaller - dexomol - Feb-22-2021 Hi, can some one show me a way to write this code in a shorter way? :) Can't find a way to make the labels configure more compact with iteration. from tkinter import * window = Tk() data = [['100%', '80%', '60%', '40%', '20%', '10%'], ['100%', '90%', '55%', '30%', '10%', '0%']] def recall1(): l1.configure(text=data[0][0]) l2.configure(text=data[0][1]) l3.configure(text=data[0][2]) l4.configure(text=data[0][3]) l5.configure(text=data[0][4]) l6.configure(text=data[0][5]) def recall2(): l1.configure(text=data[0][0]) l2.configure(text=data[1][1]) l3.configure(text=data[1][2]) l4.configure(text=data[1][3]) l5.configure(text=data[1][4]) l6.configure(text=data[1][5]) l1 = Label(window, text="...") l2 = Label(window, text="...") l3 = Label(window, text="...") l4 = Label(window, text="...") l5 = Label(window, text="...") l6 = Label(window, text="...") recallButton1 = Button(window, text="Recall Scene 1", padx=50, command=recall1) recallButton2 = Button(window, text="Recall Scene 2", padx=50, command=recall2) l1.grid() l2.grid() l3.grid() l4.grid() l5.grid() l6.grid() recallButton1.grid() recallButton2.grid() window.mainloop() RE: Please help to make the code smaller - BashBedlam - Feb-22-2021 One way to go about it would be to put all of those labels into a list like so: from tkinter import * window = Tk() data = [['100%', '80%', '60%', '40%', '20%', '10%'], ['100%', '90%', '55%', '30%', '10%', '0%']] labels = [] for x in range (6) : labels.append (Label(window, text="...")) labels [x].grid () def recall1(): for x in range (6) : labels [x].configure(text=data[0][x]) def recall2(): for x in range (6) : if x == 0 : y = 0 else : y = 1 labels [x].configure(text=data[y][x]) recallButton1 = Button(window, text="Recall Scene 1", padx=50, command=recall1) recallButton2 = Button(window, text="Recall Scene 2", padx=50, command=recall2) recallButton1.grid() recallButton2.grid() window.mainloop() RE: Please help to make the code smaller - dexomol - Feb-26-2021 (Feb-22-2021, 10:54 PM)BashBedlam Wrote: One way to go about it would be to put all of those labels into a list like so: Thank you! |