Python Tkinter Label in Frame

我的未来我决定 提交于 2021-02-05 08:33:48

问题


I want to place a label inside a frame in tkinter, but I can't figure out how to actually get it inside.

import tkinter
from tkinter import *

W=tkinter.Tk()
W.geometry("800x850+0+0")
W.configure(background="lightblue")

FRAME=Frame(W, width=100, height =50).place(x=700,y=0)

LABEL=Label(FRAME, text="test").pack()

When I run this, it doesn't place the Label inside the frame, but just places it normally on the window. What am I doing wrong?


回答1:


In the line

FRAME=Frame(W, width=100, height =50).place(x=700,y=0)

You think you are returning a tk frame, but you are not! You get the return value of the place method, which is None

So try

frame = Frame(W, width=100, height=50)
frame.place(x=700, y=0)
label = Label(frame, text="test").pack()

If you don't want the frame to shrink to fit the label, use (How to stop Tkinter Frame from shrinking to fit its contents?)

frame.pack_propagate(False) 

Note: Either import tkinter or from tkinter import * but not both. Also, by convention, names of instances of objects are lowercase.




回答2:


I think it's because you're assigning FRAME to Frame(W, width=100, height =50).place(x=700,y=0), as opposed to just the actual frame, and according to the Place Manager reference, there doesn't seem to be a return value. Try this:

import tkinter
from tkinter import *

W=tkinter.Tk()
W.geometry("800x850+0+0")
W.configure(background="lightblue")

FRAME=Frame(W, width=100, height =50)
FRAME.place(x=700,y=0)

LABEL=Label(FRAME, text="test").pack()

W.mainloop()


来源:https://stackoverflow.com/questions/39580739/python-tkinter-label-in-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!