13

我一直在玩 tkinter,但我不明白为什么“sticky”属性似乎不适用于我的按钮。我已将sticky 指定为NW,这应该会导致我的按钮粘在左上角,但由于某种原因它会粘在右上角。知道为什么吗?

from tkinter import *
from tkinter import ttk

def test():
    name = userName.get()
    text = "Hello {0}! Pleased to meet you.".format(name)
    greeting.set(text)

window = Tk()

greeting = StringVar()
userName = StringVar()

name = Entry(window, textvariable=userName)
name.grid(column=1, row=1, sticky=NW)

button = Button(window, text="greeting", command=test)
button.grid(column=2, row=1, sticky=NW)

label = Label(window, textvariable=greeting)
label.grid(column=1, row=2, sticky=NW)

#creating a rectangle
canvas = Canvas(window)
canvas.grid(column=1, row=2)
#attributes are x,y coordinates of two points
x = canvas.create_rectangle(5,5,115,115)    

mainloop()
4

2 回答 2

11

The sticky attribute applies to the cell that the widget is in, rather than to the whole grid or whole window. So, the widget is anchored to the nw corner of its cell, it's just that you can't tell because the cell is exactly the same width as the button.

Since you are placing the button in the upper right cell (row 1, column 2) but say you want it in the upper left (of the whole window?) it's hard to know exactly what you want. Without knowing what you're trying to achieve it's hard to make any recommendations.

The easiest way to learn the grid layout manager is with paper and pencil. Get out some gridded graphing paper and draw your widgets on the paper. It then becomes obvious where to put your widgets.

You also need to learn about the rowconfigure and columnconfigure commands, especially with respect to the weight attribute. With this attribute you can identify which rows and columns grown and shrink to take up any extra space. It's also useful to know you can apply these attributes to empty rows and columns. This is useful if you want your interior widgets to stay the same size, and have any extra applied to the edges of your gui (generally not useful, though sometimes it is).

As a rough rule of thumb, each window should have one "major" widget -- the one that dominates the UI. Usually this is a canvas or text widget, but it doesn't have to be. Find that widget and give the row and column it is in a weight of 1 (one) so that it grows and shrinks as the user resizes the window. In your case this would be the canvas in row 2, column 1.

于 2011-05-30T12:49:28.973 回答
1

关键是网格单元的大小与按钮的大小完全相同 - 您不会注意到它是 E 还是 W ...您可以通过将所有小部件放在彼此下方来检查这一点(所有第 0 行和第 0 列-4)您会看到在这种情况下按钮显示为 NW。希望这可以帮助...

于 2011-05-30T09:44:05.443 回答