Setting the position on a button in Python?

孤街浪徒 提交于 2019-12-17 18:57:09

问题


I just wrote a code that creates a window (using TKinter) and displays one working button.

b = Button(master, text="get", width=10, command=callback)

But i would like to have multiple buttons underneath this one.

How do you set the row and column of the button? I tried to add row = 0, column = 0, but that would not work.

Thanks


回答1:


astynax is right. To follow the example you gave:

MyButton1 = Button(master, text="BUTTON1", width=10, command=callback)
MyButton1.grid(row=0, column=0)

MyButton2 = Button(master, text="BUTTON2", width=10, command=callback)
MyButton2.grid(row=1, column=0)

MyButton3 = Button(master, text="BUTTON3", width=10, command=callback)
MyButton3.grid(row=2, column=0)

Should create 3 row of buttons. Using grid is a lot better than using pack. However, if you use grid on one button and pack on another it will not work and you will get an error.




回答2:


Causing a widget to appear requires that you position it using with what Tkinter calls "geometry managers". The three managers are grid, pack and place. Each has strengths and weaknesses. These three managers are implemented as methods on all widgets.

grid, as its name implies, is perfect for laying widgets in a grid. You can specify rows and columns, row and column spans, padding, etc.

Example:

b = Button(...)
b.grid(row=2, column=3, columnspan=2)

pack uses a box metaphor, letting you "pack" widgets along one of the sides of a container. pack is extremely good at all-vertical or all-horizontal layouts. Toolbars, for example, where widgets are aligned in a horizontal line, are a good place to use pack.

Example:

b = Button(...)
b.pack(side="top", fill='both', expand=True, padx=4, pady=4)`

place is the least used geometry manager. With place you specify the exact x/y location and exact width/height for a widget. It has some nice features such as being able to use either absolute or relative coordinates (for example: you can place a widget at 10,10, or at 50% of the widgets width or height).

Unlike grid and pack, using place does not cause the parent widget to expand or collapse to fit all of the widgets that have been placed inside.

Example:

b = Button(...)
b.place(relx=.5, rely=.5, anchor="c")

With those three geometry managers you can do just about any type of layout you can imagine.




回答3:


Try Grid Geometry Manager:

btns = [
    (lambda ctl: ctl.grid(row=r, column=c) or ctl)(
        Button(text=str(1 + r * 3 + c)))
    for c in (0,1,2) for r in (0,1,2)]

result:

[1][2][3]
[4][5][6]
[7][8][9]


来源:https://stackoverflow.com/questions/10927234/setting-the-position-on-a-button-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!