Home > Mobile >  Adding Tkinter Buttons to a list without .append
Adding Tkinter Buttons to a list without .append

Time:05-31

I'm currently having a play around with tkinter trying to make my code efficient. I want to be able to index my buttons at a later date so I'm trying to put then into a list without first creating a blank list and appending them to it as I loop (The only way I currently know how to do it). I've got the below currently going on but at the moment every time the loop runs it overwrites my button at index 0 rather than appending to the list, how would I go about using something like this or use list comprehension to create my buttons?

for btn in range (6):
            self.Preset_Lbl = [tk.Button(self.window, width = 5, height = 1, text = mylist[0] 
            [btn], relief = "groove")]
            self.Preset_Lbl[btn].grid(row = btn, column = 1)

thanks in advance

CodePudding user response:

trying to make my code efficient

In general, you should only bother to optimize code after it has been proven (by measurements, i.e. through profiling) that it is a major bottleneck.

First, optimizations can often make code more complicated and difficult to read and understand.

Second, you don't know what the bottlenecks in your code are before you measure them. For example, in my stl2pov program, it turned out that string formatting was actually consuming most of the time. And using the appropriate type specifier to the format string halved the necessary time. Another example is where replacing statistics.mean with statistics.fmean reduced the runtime by about a third.

CodePudding user response:

In contrast to the comments, you can indeed create a list variable and initialize all its values in the same line as such without needing to loop through it:

self.Preset_lbl = [tk.Button(self.window, width=5, height=1, text=mylist[0][btn], relief="groove") for btn in range(6)]

You need to decide for yourself, if you care about the readability of this approach or you can also check if it would impact performance in any way by profiling/benchmarking it like stated by Roland Smith.

  • Related