繁体   English   中英

Tkinter:2 个相邻的按钮使用 window 调整宽度。如何?

[英]Tkinter: 2 buttons next to each other resize in width with window. How to?

2 个按钮应该分别占用 window 的一半,一个在左边,一个在右边。 高度始终是固定的。 使用.grid().place()我可以得到那个结果。 红色条是放置按钮的框架的颜色。 使用 window 调整按钮的宽度,但保持其恒定高度。

如何?

在此处输入图像描述

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red')
frame.pack(fill='both', expand=True)

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.grid(row=0, column=0, sticky='nsew')
button2.grid(row=0, column=1, sticky='nsew')

frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, weight=1)

root.mainloop()

谢谢。 与此同时,我得到了这个:

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red',height=30)
frame.pack(fill='both')

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.place(relwidth=0.5, relx=0, relheight=1)
button2.place(relwidth=0.5, relx=0.5, relheight=1)

root.mainloop()

假设按钮是框架中唯一的小部件(即:您正在制作工具栏),我会使用pack grid也可以,但它需要额外的一行代码。

使用包

这是带有pack的版本。 请注意,框架沿顶部打包,并在“x”方向填充 window。 每个按钮都被指示展开(即:接收额外的、未使用的空间)并填充在“x”方向上分配给它们的空间。

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red',height=30)
frame.pack(side="top", fill="x")

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.pack(side="left", fill="x", expand=True)
button2.pack(side="right", fill="x", expand=True)

root.mainloop()

使用网格

带有grid的版本类似,但您必须使用columnconfigure为两列赋予非零权重:

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red',height=30)
frame.pack(side="top", fill="x")

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.grid(row=0, column=0, sticky="ew")
button2.grid(row=0, column=1, sticky="ew")

frame.grid_columnconfigure((0, 1), weight=1)

root.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM