Python 多个按钮Tkinter-画布上的位置

Python 多个按钮Tkinter-画布上的位置,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我发现一些代码(堆栈溢出的补充)可以在画布上创建多个按钮。 我想学习的是如何将多个按钮放置在画布上的任何地方,例如按钮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.Fram

我发现一些代码(堆栈溢出的补充)可以在画布上创建多个按钮。 我想学习的是如何将多个按钮放置在画布上的任何地方,例如按钮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)]

非常感谢。这两段代码都工作得很好——对于嵌套循环代码,如何替换text=str(x)+'x'+str(y)对于字典中的项目,因此每个按钮文本将为0000 0020 0040等谢谢-我知道字典键如何与值相关,以及我如何使用这些值添加一系列按钮您的第一步应该是学习tkinter教程。Stackoverflow不是免费的编码服务。