我试图将Label小部件中的文本放在右侧。我已经将锚设置为E,但除非我为Label指定宽度,否则文本将不会移动。
我不想为Label小部件设置特定的宽度,因为它应该与下面框架中的按钮的宽度相同,因为按钮的大小可能会发生变化(这只是一个试用版我躺在那里的一些样本gif。)
以下是我正在使用的代码:
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()
答案 0 :(得分:1)
问题来自包含小部件f1
。只要它只是一个具有默认网格值的框架,它只会扩展到足以容纳其包含和居中的任何内容:
您需要指定sticky
值才能在其行或列中移动Frame。在这种情况下,您可以将其设置为E
以将其移至东部:
f1 = Frame(parent)
f1.grid(row=0, column=0, sticky=E)
Label(f1, text='0').pack()
更多:http://effbot.org/tkinterbook/grid.htm#Tkinter.Grid.grid-method