简体   繁体   English

使用pack()或grid()填充框架时出现问题

[英]Problems using either pack() or grid() to fill a frame

I am attempting to get the text inside the Label widget to be on the right hand side. 我正在尝试使“标签”小部件内的文本位于右侧。 I have set the anchor to E but unless I specify a width for the Label the text will not move. 我已将锚设置为E,但除非为Label指定宽度,否则文本将不会移动。

I don't want to set a specific width for the Label widget as it should be the same width as the buttons in the frame below and as the size of the buttons may well change (this was only a trial with some sample gif's I had lying around). 我不想为Label小部件设置特定的宽度,因为它应该与下方框架中的按钮具有相同的宽度,并且按钮的大小可能会发生变化(这只是一些示例gif的试用版,躺着)。

Here is the code I am using: 这是我正在使用的代码:

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()

The problem comes from the containing widget, f1 . 问题来自于包含的小部件f1 As long as it's just a Frame with default grid values, it is only going to expand enough to hold whatever it's containing and center itself: 只要它是具有默认网格值的框架,它就只会扩展到足以容纳它所包含的内容并居中放置:

框架小部件

You need to specify a sticky value to move the Frame within its row or column. 您需要指定一个sticky值,才能在框架的行或列中移动框架。 In this case, you can set it to E to move it to the east: 在这种情况下,可以将其设置为E以将其向东移动:

f1 = Frame(parent)
f1.grid(row=0, column=0, sticky=E)

Label(f1, text='0').pack()

More: http://effbot.org/tkinterbook/grid.htm#Tkinter.Grid.grid-method 更多: http : //effbot.org/tkinterbook/grid.htm#Tkinter.Grid.grid-method

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

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