在 tkinter 和 python 中嵌套网格和框架

编程入门 行业动态 更新时间:2024-10-18 02:26:26
本文介绍了在 tkinter 和 python 中嵌套网格和框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试在较大网格结构中的框架内设置网格.我已经尝试将其提炼为问题的最简单版本.

from tkinter import Tk, Frame, Label, Entry根 = Tk()root.geometry('800x800')框架1 = 框架(根,宽度= 400,高度= 400,背景=蓝色")frame2 = 框架(根,宽度=400,高度=400,背景=红色")frame1.grid(row=0, column=0)frame2.grid(行=1,列=1)label1 = Label(frame1,text='Label1')label1.grid()

不是将标签放置在 frame1 内部,而是标签替换了整个网格中的框架:

我查看了其他示例,但我无法确定它们为何有效,而我的却没有.

解决方案

使用 jasonharper 的观察,即 Frame 会自动调整自身大小,并发布了一个类似的问题

I'm trying to set up a grid inside of a frame which is in a larger grid structure. I've tried to distill it to the simplest version of the problem.

from tkinter import Tk, Frame, Label, Entry

root = Tk()
root.geometry('800x800')


frame1 = Frame(root, width=400, height=400, background="Blue")
frame2 = Frame(root, width=400, height=400, background="Red")

frame1.grid(row=0, column=0)
frame2.grid(row=1, column=1)

label1 = Label(frame1,text='Label1')
label1.grid()

Instead of placing the label inside of frame1, the label replaces the frame in the overall grid:

I've looked at other examples, but I haven't been able to identify why they work and mine does not.

解决方案

Using jasonharper's observation that the Frame was automatically resizing itself and a similar question posted here, I was able to update the code.

from tkinter import Tk, Frame, Label

root = Tk()
root.geometry('800x800')

root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(1, weight=1)

frame1 = Frame(root, background="Blue")
frame2 = Frame(root, background="Red")

frame1.grid(row=0, column=0, sticky="nsew")
frame2.grid(row=1, column=1, sticky="nsew")


label1 = Label(frame1,text='Label1')
label1.grid()

The changes that I made to the code are:

I removed the height and width parameters from the Frame instances because they weren't doing anything anyway. Added weighting to the rows and columns of root, the container for the frames, to equally space the frames in the available space Add the 'sticky' parameter to the grid placements of the frames so that the frames would take up all of the space that they were allotted.

The result:

这篇关于在 tkinter 和 python 中嵌套网格和框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 07:13:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390659.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   网格   框架   tkinter   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!