Overcoming Slow Button And Frame Display And Patchy Backgrounds For A Custom Buttonframe During Frame Resizing.
I have written an algorithm that allows a ttk.Frame to wrap multiple buttons within it such that when the buttons take up too much space horizontally the affected buttons will auto
Solution 1:
The best thing you can do is stop creating new widgets on every <Configure>
event. Create them once, then move them only when you've computed that they need to move. When I resize the main window just wide enough to create a single row, your code will have created anywhere from 200 to 2000 buttons or more depending on how fast I do the resize.
An alternate solution
You might want to consider using grid
rather than pack
, since grid
doesn't require that you create internal frames for each row.
Here's a quick and dirty example to illustrate the concept. It hasn't been tested much, but it seems to work:
import tkinter as tk
import tkinter.ttk as ttk
classFrameButtons(ttk.Frame):
def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.buttons = []
self.bind("<Configure>", self._redraw)
def_redraw(self, event=None):
maxwidth = self.winfo_width()
row = column = rowwidth = 0for button in self.buttons:
# will it fit? If not, move to the next rowif rowwidth + button.winfo_width() > maxwidth:
row += 1
column = 0
rowwidth = 0
rowwidth += button.winfo_width()
button.grid(row=row, column=column)
column += 1defadd_button(self, *args, **kwargs):
'''Add one button to the frame'''
button = ttk.Button(self, *args, **kwargs)
self.buttons.append(button)
self._redraw()
if __name__ == "__main__":
root = tk.Tk()
button_frame = FrameButtons(root)
button_frame.pack(side="top", fill="x", expand=False)
for i inrange(20):
button_frame.add_button(text=str(i))
root.mainloop()
Post a Comment for "Overcoming Slow Button And Frame Display And Patchy Backgrounds For A Custom Buttonframe During Frame Resizing."