多按钮Tkinter-在画布上的位置

时间:2018-09-23 08:21:42

标签: python python-3.x tkinter

我找到了一些代码(堆栈溢出的补充),这些代码将在画布上创建多个按钮。 我想学习的是如何将这些多个按钮放置在画布上的任何位置,例如按钮1按钮2按钮3等,并将它们放置在画布中间。另外,如果我说了50个按钮,我怎么能以10 x 5的格式显示它们?

<td>{{ courseOrder.orderDate|date('Y/m/d') }}</td>

1 个答案:

答案 0 :(得分:2)

您将小部件放置在具有create_window()的画布上,该画布需要x和y坐标,高度,宽度和小部件参考(以及锚点)。

请参见以下示例:

from tkinter import *
from tkinter import ttk
from functools import partial

root = Tk()
root.title('test')
root.resizable(False, False)
root.geometry('800x400')
root.columnconfigure(0, weight=1)   # Which column should expand with window
root.rowconfigure(0, weight=1)      # Which row should expand with window

items = [{'name' : '1', 'text' : '0000', 'x': 0, 'y': 0},
         {'name' : '2', 'text' : '0020', 'x': 55, 'y': 150},
         {'name' : '3', 'text' : '0040', 'x': 600, 'y': 200}]

canvas = Canvas(root, bg='khaki')   # To see where canvas is
canvas.grid(sticky=NSEW)

for item in items:
    widget = ttk.Button(root, text=item['text'],
                        command=partial(print,item['text']))
    # Place widget on canvas with: create_window
    canvas.create_window(item['x'], item['y'], anchor=NW, 
                         height=25, width=70, window=widget)

root.mainloop()

要获取10 x 5格式的按钮,只需使用嵌套的for循环即可。

for x in range(10):
    for y in range(5):
        text = str(x) + ' x ' + str(y)
        widget = ttk.Button(root, text=text,
                            command=partial(print,text))
        # Place widget on canvas with: create_window
        canvas.create_window(10+75*x, 10+30*y, anchor=NW, 
                             height=25, width=70, window=widget)

命名所有按钮的最简单方法可能是制作一个将名称与位置相关联的字典:

text_dict = {'0 x 0': '0000',
             '1 x 0': '0020'
             # etc, etc.
             }

,然后使用dict设置按钮文本:

text = text_dict[str(x) + ' x ' + str(y)]