使用pack()或grid()填充帧时出现问题
我试图使标签小部件中的文本位于右侧。我已将锚定设置为E,但除非为标签指定宽度,否则文本将不会移动 我不想为标签小部件设置一个特定的宽度,因为它应该与下面框架中的按钮宽度相同,并且按钮的大小可能会发生变化(这只是对我周围的一些示例gif的一次尝试) 以下是我正在使用的代码:使用pack()或grid()填充帧时出现问题,grid,tkinter,pack,Grid,Tkinter,Pack,我试图使标签小部件中的文本位于右侧。我已将锚定设置为E,但除非为标签指定宽度,否则文本将不会移动 我不想为标签小部件设置一个特定的宽度,因为它应该与下面框架中的按钮宽度相同,并且按钮的大小可能会发生变化(这只是对我周围的一些示例gif的一次尝试) 以下是我正在使用的代码: from tkinter import* class CalculatorFrame: def __init__(self, parent): f1 = Frame(parent) f1
from tkinter import*
class CalculatorFrame:
def __init__(self, parent):
f1 = Frame(parent)
f1.grid(row = 0, column = 0)
label1 = Label(f1, anchor = E, text = "0")
label1.pack(fill = X)
f2 = Frame(parent)
f2.grid(row = 1, column = 0)
self.buttons = []
image_names = ["bus.gif", "plane.gif", "train.gif", "satellite.gif", "house.gif", "ship.gif", "satellite.gif", "plane.gif"]
for i in range(len(image_names)):
self.buttons.append(Button(f2, width = 90, height = 70, text=str(i)))
self.buttons[i].img = PhotoImage(file = image_names[i])
self.buttons[i].configure(image = self.buttons[i].img)
i = 0
for r in range(2):
for c in range(4):
self.buttons[i].grid(row = r, column = c)
i += 1
if __name__ == '__main__':
root = Tk()
game = CalculatorFrame(root)
root.mainloop()
问题来自包含的小部件,
f1
。只要它只是一个带有默认网格值的框架,它只会扩展到足以容纳它所包含的内容并将其自身居中:
您需要指定一个sticky
值以在其行或列内移动框架。在这种情况下,您可以将其设置为E
,将其向东移动:
f1 = Frame(parent)
f1.grid(row=0, column=0, sticky=E)
Label(f1, text='0').pack()
更多: