在框架内放置 Tkinter 小部件的问题 [英] Issue with placing Tkinter widgets within frame

查看:24
本文介绍了在框架内放置 Tkinter 小部件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 Tkinter,但遇到一个非常简单的问题,让我发疯.我正在尝试在标签框架内放置一个按钮.这是一项非常简单的任务,有许多在线教程.只需创建按钮并将框架指定为父级即可.然后使用 pack 命令将小部件打包到其父级中.但是,当我这样做时,按钮 - 或任何小部件 - 总是在父项下.无论我使用包还是网格,子小部件始终在其下方.参考这张图片

I've just started using Tkinter, and I'm having a very simple issue that is driving me insane. I'm trying to place a button within a label frame. It's a very simple task with many tutorials online. Simply create the button and assign the frame as the parent. Then use the pack command to pack the widget within its parent. However, when I do this the button - or any widget - is always under the parent. No matter whether I use pack or grid, the child widget is always beneath it. Refer to this image

from tkinter import *

application = Tk()
lblframe = LabelFrame(application, width=300, height=300, text="Test", bd=10).pack()
btn = Button(lblframe, text="Button 1").pack()
application.mainloop()

推荐答案

pack() 返回的值为 None.因此,您正在分配 lblframe 以保存 None 值,因此当您创建 Button 小部件时,它已将 None 作为父级传递.这导致它的父级成为应用程序的顶层,因此你看到的打包(两个小部件都打包到同一个容器中).如果您分别进行创建和打包,它将按您的预期工作,例如:

The value returned by pack() is None. So you are assigning lblframe to hold a value of None and therefore when you create the Button widget it has None passed as the parent. That causes its parent to be the application toplevel hence the packing you see (both widgets are packed into the same container). If you do the creation and packing separately it will work as you expect eg:

from tkinter import *

application = Tk()
lblframe = LabelFrame(application, width=300, height=300, text="Test", bd=10)
btn = Button(lblframe, text="Button 1")
lblframe.pack()
btn.pack()
application.mainloop()

这篇关于在框架内放置 Tkinter 小部件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆