How to stop the resizing of the Tkinter Text widget when changing the font?

I am trying to create a simple word processor for beginners to learn a little Python.

I use the Tkinter widget Textfor the main editing program, the only problem is the height and width defined by the characters.

This creates a problem when changing fonts, because not all fonts have the same width.

Each time the font changes, the Text widget changes size, although technically it has the same width and height. It looks ridiculous when you try to print something, I try to make the word processor as pleasant as possible.

Is there a way to determine the width and height in pixels?

.grid_propagate(False) not useful for size, technically unchanged, only character width.

I am trying to stay away from wxPythonsince everything that I have done so far has been in Tkinter.

I spent endless hours of extensive searching, but couldn't find a solution.

+6
source share
2 answers

You are mistaken when you say that you cannot use grid_propagate(False)because you can. grid_propagatelinked to the actual size, not the size attribute. Also, if you just give your application a fixed size with wm_geometry, font changes will not affect the window size.

Here is a usage example grid_propagatethat sets a container to a fixed size in pixels:

import Tkinter as tk
import tkFont

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self._textFont = tkFont.Font(name="TextFont")
        self._textFont.configure(**tkFont.nametofont("TkDefaultFont").configure())

        toolbar = tk.Frame(self, borderwidth=0)
        container = tk.Frame(self, borderwidth=1, relief="sunken", 
                             width=600, height=600)
        container.grid_propagate(False)
        toolbar.pack(side="top", fill="x")
        container.pack(side="bottom", fill="both", expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        text = tk.Text(container, font="TextFont")
        text.grid(row=0, column=0, sticky="nsew")

        zoomin = tk.Button(toolbar, text="+", command=self.zoom_in)
        zoomout = tk.Button(toolbar, text="-", command=self.zoom_out)
        zoomin.pack(side="left")
        zoomout.pack(side="left")

        text.insert("end", '''Press te + and - buttons to increase or decrease the font size''')

    def zoom_in(self):
        font = tkFont.nametofont("TextFont")
        size = font.actual()["size"]+2
        font.configure(size=size)

    def zoom_out(self):
        font = tkFont.nametofont("TextFont")
        size = font.actual()["size"]-2
        font.configure(size=max(size, 8))

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()
+10
source

... : , () . , - 2 , , , .

grid_propagate, * _row- * _columnconfigure - , main- -, ... - , scrolledtext- ( ).

0

All Articles