Home > database >  Grid not work correctly - Tkinter GUI library - python
Grid not work correctly - Tkinter GUI library - python

Time:08-26

This is the result of my code GUI Result

I got 2 problems here.

First one, In my code at Line 10, I create a Frame widget with bg="#ffde00" (Similar to yellow). then I put 2 widget in it with grid() method. After that, I couldn't able to see Frame's background color. So I decide to add bg="#ffde00" to those 2 widget (photo_widget & title_widget). Here, I faced the second problem. The grid method not work correctly . Both widget didn't placed at top.

Here's my code

import tkinter
from tkinter import *
from PIL import ImageTk, Image

app = Tk()
app.title("Test")
app.resizable(False,False)

# Left Side Area
leftside_area = Frame(app,width=250,height=450,bg="#ffde00")
leftside_area.grid(row=0,column=0,sticky="ew")

# Main Area
main_area = Frame(app,width=450,height=450,bg="#8601af",border=-2)
main_area.grid(row=0,column=1,sticky="ew")

# Photo (Left side)
photo = ImageTk.PhotoImage(Image.open("logo.png").resize((200,200)))
photo_widget = Label(leftside_area,image=photo,bg="#ffde00")
photo_widget.grid(row=0,column=0,sticky="new")

# Title (Left side)
title_widget = Label(leftside_area,text="test",bg="#ffde00")
title_widget.grid(row=1,column=0,sticky="w")

app.mainloop()

CodePudding user response:

How about changing the leftside_area to sticky="news"?

leftside_area.grid(row=0,column=0,sticky="news")

I believe if you add widgets to a Frame, the Frame shrinks to fit the widgets, unless you tell it to stick to the edges of its width and height. In other words, add sticky="news".

CodePudding user response:

The problem was : I was create 2 Frame first and pack them up, then add other widget in them.

But now I write code like this :

import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image

app = Tk()
app.geometry("700x450")
app.resizable(False,False)

# Left Side Area
frame1 = Frame(app,width=250,height=450,bg="#ffde00")
frame1.columnconfigure(0,weight=1)

# Photo (Left side)
photo = ImageTk.PhotoImage(Image.open("logo.png").resize((200,200)))
photo_lable = Label(frame1,image=photo,bg="#ffde00").grid(row=0,column=0,columnspan=1,sticky="we")

# Title (Left side)
text_lable = Label(frame1,text="hi",bg="#ffde00").grid(row=1,column=0,columnspan=1,sticky="we")

frame1.pack(side=LEFT,fill="both",expand=True)


# Main Area
frame2 = Frame(app,width=450,height=450,bg="#8601af")
frame2.pack(side=LEFT)

app.mainloop()

Now it working correct. GUI result

  • Related