简体   繁体   中英

Python tkinter how to zoom in widgets

My code:

import tkinter as tk

root = tk.Tk()

for i in range(50):
    for j in range(50):
        tk.Button(height=1, width=2, bg='Blue').grid(row=j, column=i)

root.mainloop()

I can not see all of the buttons in the screen even when I maxmize the window. so I want to add an option to zoom out (all of the widgets will be smaller) so I can see all of them. How do I do that?

From what i have been able to understand from your question, i think you want the window to be resizable in tkinter.

To allow a window to be resized by the user, we use the resizable function -:

root.resizable(height = True, width = True)

In this case the two args are height and width which help you customize if you only want the widget to be vertically resizable or only want it to be horizontally resizable.

Your code with this function added should look like this -:

import tkinter as tk

root = tk.Tk()
root.resizable(True, True) #Assuming you want both vertically and horizontally resizable window.

for i in range(50):
    for j in range(50):
        tk.Button(height=1, width=2, bg='Blue').grid(row=j, column=i)

root.mainloop()

I hope this will solve your problem. And I also hope you are safe in this time of an ongoing pandemic.

Example code:

import tkinter as tk

root = tk.Tk()
root.state('zoomed')
widgets_to_zoom_list = []
DEFAULT_SIZE = 50


def zoom(widget):
    for every_widget in widgets_to_zoom_list:
        every_widget.config(width=widget.get(), height=widget.get())


def main():
    canvas = tk.Canvas(root)
    frame = tk.Frame(canvas)
    zoom_scale = tk.Scale(root, orient='vertical', from_=1, to=100)
    zoom_scale.config(command=lambda args: zoom(zoom_scale))

    zoom_scale.set(DEFAULT_SIZE)

    pixel = tk.PhotoImage(width=1, height=1)
    for i in range(50):
        btn = tk.Button(frame, text=str(i + 1), bg='Blue', image=pixel, width=DEFAULT_SIZE, height=DEFAULT_SIZE, compound="c")
        btn.grid(row=0, column=i)
        widgets_to_zoom_list.append(btn)

    canvas.create_window(0, 0, anchor='nw', window=frame)
    # make sure everything is displayed before configuring the scroll region
    canvas.update_idletasks()

    canvas.configure(scrollregion=canvas.bbox('all'))
    canvas.pack(fill='both', side='left', expand=True)
    zoom_scale.pack(fill='y', side='right')
    root.mainloop()


if __name__ == '__main__':
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM