我找到了一些代码(堆栈溢出的补充),可以在 Canvas 上创建多个按钮。 我想学习的是如何将这些多个按钮放置在 Canvas 上的任何位置,例如按钮 1、按钮 2、按钮 3 等,并将它们放在 Canvas 的中间。另外,如果我说有 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()
将小部件放在 Canvas 上,它采用 x 和 y 坐标、高度、宽度和小部件引用(和 anchor )。
参见下面的示例:
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.
}
然后使用字典设置按钮文本:
text = text_dict[str(x) + ' x ' + str(y)]
关于python - 多个按钮 Tkinter - Canvas 上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52464307/