user4215369
user4215369

Reputation:

Text widget to fill half of screen

I have a python tkinter program and i have two text widgets that need to be side by side. How can i get the two widgets to take up exactly half of the window which is 400 x 400 px ?

My Code is here

import tkinter

class MyApp:
    def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("App")
        self.root.geometry("400x400")
        self.root.update()
        self.box1Text = tkinter.Text(self.root)
        self.box1Text.pack(fill=tkinter.BOTH,side=tkinter.LEFT)
        self.box2Text = tkinter.Text(self.root)
        self.box2Text.pack(fill=tkinter.BOTH,side=tkinter.RIGHT)

App = MyApp()

Upvotes: 1

Views: 2708

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386285

By default the text widget wants to be 80 characters wide by 24 characters tall. If you don't specify a size, tkinter will do its best to make sure the widget is that size. If it can't fit all the widgets at their requested size it will start shrinking widgets, starting with the last widget created. That is why the first widget takes up all (or most) of the window -- tkinter tries to display it, and then will give any left-over room to the next widget. In this case there is zero left over room.

Since you are giving the window an explicit size, you can give the text widget a width and height of 1 (one), and then let the geometry manager expand the widget to fill the extra space. You also need to tell pack to let the widget expand. So, add width=1, height=1 to the definition of the widgets, and then add expand=True when packing the widgets in the frame.

Here is a working example:

import tkinter

class MyApp:
    def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("App")
        self.root.geometry("400x400")
        self.root.update()
        self.box1Text = tkinter.Text(self.root, width=1, height=1)
        self.box1Text.pack(fill=tkinter.BOTH,side=tkinter.LEFT, expand=True)
        self.box2Text = tkinter.Text(self.root, width=1, height=1)
        self.box2Text.pack(fill=tkinter.BOTH,side=tkinter.RIGHT, expand=True)

App = MyApp()
App.root.mainloop()

Upvotes: 4

Related Questions