Home > OS >  Tkinter Frame-How to fix Resulation Problem while adding Label
Tkinter Frame-How to fix Resulation Problem while adding Label

Time:09-25

I'm Bloodly Beginner in Python. I was learning to create tabs in python using tkinter pkg. I have successfully created 2 tabs, but I can't show Text (Label) in both tab. When I show only 1 text in one tab (heading.pack()) it works perfectly. But when I show another text in Tab 2 (heading2.pack()), The frame Resulation Broked. I have also set width and height in Frame Option. I want to fix resulation(Before adding 2nd text resulation). Here is Before and after Screenshots

Before adding 2nd Text
After adding 2nd Text

Here is The Code:

from tkinter import *
from tkinter import ttk

root=Tk()
root.title('Tab Widget')
root.geometry('600x400')

book=ttk.Notebook(root)
book.pack(pady=2)

tab1=Frame(book,width=600,height=500,bg='white')
tab2=Frame(book,width=600,height=500,bg='white')

tab1.pack(fill='both',expand=1)
tab2.pack(fill='both',expand=1)

book.add(tab1,text='Tab 1')
book.add(tab2,text='Tab 2')

heading=Label(tab1,text='This is Tab 1',font='arial 20 bold',bg='white')
heading2=Label(tab2,text='This is Tab 2',font='arial 20 bold',bg='white')

heading.pack() #Show Text in Tab 1
heading2.pack() #Show Text in Tab 2

root.mainloop()

CodePudding user response:

When you call heading.pack(), tab1 will be shrink to the size of the label. And if you don't call heading2.pack(), tab2 will still have size 600x500. So the notebook client area will be kept at 600x500.

However when you call heading2.pack(), tab2 will be shrink to the size of the label as well which cause the notebook client area to be shrink as well.

You can avoid the above size adjustment by changing:

book.pack(pady=2)

to

book.pack(pady=2, fill='both', expand=1)

so that notebook will use all the available space of the root window.

Also note that the following two lines are not necessary and can be removed:

tab1.pack(fill='both',expand=1)
tab2.pack(fill='both',expand=1)
  • Related