当前位置: 代码迷 >> python >> 多按钮Tkinter-在画布上的位置
  详细解决方案

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

热度:69   发布时间:2023-07-14 08:59:47.0

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

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

  root = Tk()
  root.title('test')

  mainframe = ttk.Frame(root, padding='1')
  mainframe.grid(column=0, row=0)

  root.resizable(False, False)                 
  root.geometry('800x400')

  items = [
      {
          'name' : '1',
          'text' : '0000',
      },{
          'name' : '2',
          'text' : '0020',
      },{
          'name' : '3',
          'text' : '0040',
      },
  ]

  rcount = 1 

  for rcount, item in enumerate(items, start=1): 
     ttk.Button(mainframe, text=item['text'], 
  command=partial(print,item['text'])).grid(column=1, row=rcount, sticky=W)

  root.mainloop() 

您可以使用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)]
  相关解决方案