Zoom In and Out in Text widget tkinter

Viewed 732

I am trying to make a clone of Notepad but stuck in zoom in and zoom out functionality. I was able to make a zoom in and out functionality by changing the text size each time user presses the zoom in and out option but I think it is not the real implementation because I think it is not actually zooming in or zooming out.

With lots of searching I came to know that Canvas have scale method which can be used to implement the zoom-in functionality and I am able make functionality to zoom in and out of the text widget but it does not affect the text sizes. And according to this the scale method in Canvas only changes the coordinates of the widgets.

What have I done so far?

import tkinter as tk

root = tk.Tk()
root.state('zoomed')
font = ('Courier', 10)


def zoom(zoom_scale):
    global font

    font = (font[0],) + (font[1] + 1,)
    text.config(font=font)


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

zoom_scale.set(10)

text = tk.Text(frame, font=font)
text.grid(row=0, column=0)

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()

In Notepad, the text size does not increase. I think the text-widget is zooming keeping the text-size same. So how can I make a functionality to zoom in and out of the TEXT like NOTEPAD?

1 Answers

Scaling the canvas will not cause embedded widgets to grow or shrink. The only way to implement zoom is to change the size of the font in the text widget.

The following code is a modified version of your code. The things to notice are:

  • the code uses a Font object for the font
  • the scale doesn't use lambda; instead it directly calls zoom
  • zoom will configure the size of the font object, which causes the text widget to zoom
  • the canvas and frame inside the canvas have been removed.
  • the root widget has been given an explicit size via geometry, to keep the window from growing and shrinking when the text widget grows or shrinks

import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
root.geometry("500x500")
font = Font(family="Courier", size=10)

def zoom(size):
    font.configure(size=size)

zoom_scale = tk.Scale(root, orient='vertical', from_=1, to=500)
zoom_scale.config(command=zoom)
text = tk.Text(root, font=font)

zoom_scale.pack(fill='y', side='right')
text.pack(side="left", fill="both", expand=True)

zoom_scale.set(10)

root.mainloop()
Related