tkinter 生成带有名称的按钮,并在单击时将名称作为参数传递

tkinter generate buttons with names and pass names as an argument when clicked

我有一个代码可以生成 12 个按钮,这些按钮的名称来自列表。我想将这些名称传递给一个函数,但目前只记住来自按钮的最后一个文本,并且它被用于所有按钮。 有没有办法(除了手动创建所有按钮)让它起作用,这意味着正确的按钮名称将被进一步传递?

import tkinter as tk
from tkinter import *

notes_list = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
c = 0
r = 0

def notes(note):

    major_scale_steps = [2,2,1,2,2,2,1]
    minor_scale_notes = [2,1,2,2,1,2,2]

    #find where provided note is located and rearrange notes_list accordingly
    ind = notes_list.index(note)
    n_tran = notes_list[ind:]+notes_list[:ind]

    #gather notes using major_scale_steps
    major_scale = [n_tran[0],n_tran[2],n_tran[4],n_tran[5],n_tran[7],n_tran[9], n_tran[11], n_tran[0]]
    minor_scale = [n_tran[0],n_tran[2],n_tran[3],n_tran[5],n_tran[7],n_tran[8], n_tran[10], n_tran[0]]

    return major_scale

def clicked():
    te = notes(i.config('text')[-1])
    #place label with results
    test = tk.Label(window, text=te)
    test.place(x=100, y=150)
    

window = tk.Tk()
window.title('Guitar notes')
window.geometry('320x250')

#create buttons
for i in notes_list:
    i = Button(window, text=i, command=clicked)
    i.config(height=2, width=10)
    i.grid(column=c, row=r)
    c+=1
    if c == 4:
        c=0
        r+=1


window.mainloop()

因为你在clicked()里面用了i。当执行clicked()时,i将是主for循环中最后创建的按钮。

您应该使用 functools.partial() 将所需的 note 传递给 clicked(),并使用此 note 更新 test 标签。

最好在 clicked() 之外创建 test 标签,并在函数内更新其文本。

import tkinter as tk
from functools import partial

notes_list = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']

def notes(note):
    #major_scale_steps = [2,2,1,2,2,2,1]
    #minor_scale_notes = [2,1,2,2,1,2,2]

    #find where provided note is located and rearrange notes_list accordingly
    ind = notes_list.index(note)
    n_tran = notes_list[ind:]+notes_list[:ind]

    #gather notes using major_scale_steps
    major_scale = [n_tran[0],n_tran[2],n_tran[4],n_tran[5],n_tran[7],n_tran[9], n_tran[11], n_tran[0]]
    # shorter version of above:
    #major_scale = [n_tran[x] for x in (0, 2, 4, 5, 7, 9, 11, 0)]
    #minor_scale = [n_tran[0],n_tran[2],n_tran[3],n_tran[5],n_tran[7],n_tran[8], n_tran[10], n_tran[0]]

    return major_scale

def clicked(note):
    # update test label
    test.config(text=notes(note))

window = tk.Tk()
window.title('Guitar notes')
window.geometry('320x250')

# create test label here
test = tk.Label(window)
test.place(x=100, y=150)

#create buttons
for i, note in enumerate(notes_list):
    btn = tk.Button(window, text=note, width=10, height=2, command=partial(clicked, note))
    btn.grid(column=i%4, row=i//4)

window.mainloop()