如何取回按钮按下的值而不是破坏窗口?

时间:2017-01-28 12:27:13

标签: python tkinter

如何更改我的代码,以便我可以使用按下的按钮的值,而不是破坏窗口?

from tkinter import *

window=Tk()
window.geometry('905x560')

letters=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]


for i in range(len(letters)):

    ButtonLetter=Button(window, text=letters[i], command=window.destroy)
    ButtonLetter.place(x=905/9*(i-((i//9)*9))+35, y=225+100*(i//9))

window.mainloop()

1 个答案:

答案 0 :(得分:0)

您需要将按钮中的command=window.destroy更改为您要呼叫的所需功能。

将按钮定义更改为以下内容,以便您使用按下的按钮名称作为参数调用您的函数:

ButtonLetter=Button(window, text=letters[i], command=lambda name=letters[i]:pressed(name))

例如运行此代码:

from Tkinter import *

window=Tk()
window.geometry('905x560')

letters=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

def pressed(label):
    print label

for i in range(len(letters)):
    ButtonLetter=Button(window, text=letters[i], command = lambda name=letters[i]:pressed(name))
    ButtonLetter.place(x=905/9*(i-((i//9)*9))+35, y=225+100*(i//9))

window.mainloop()