如何在Tkinter中将按钮连接到字典

时间:2019-06-10 15:10:07

标签: python dictionary user-interface tkinter

运行此代码时,我想创建一堆按钮。然后,如果您单击该按钮,我想在我的词典中显示与该按钮相对应的内容。

我已经创建了词典并填充了词典,但是我只是不知道如何告诉按钮在词典中查找该单词。到目前为止,这就是我所拥有的,我只是想知道如何做到这一点,因此您单击按钮,相应的文本就会打印到终端上。到目前为止,这仅导致根据单词列表(二维数组)在网格中创建按钮。我的字典称为my_dict,而show_content应该以wordList [x] [y]的值打印字典中的内容。

def url_entry():
    for y in range(len(wordList)):
        WebScrape.yolo(e1.get(), wordList[y], countList[y],my_dict)
        for x in range(len(wordList[y])):
            if countList[y][x] > 0:
                text_to_use = '{0} \n({1})'.format(wordList[y][x], countList[y][x])
                tk.Button(text=text_to_use, relief=tk.RIDGE, width=15, command=show_content).grid(row=5 + x,column=y)
def show_content():
    print(my_dict[x])```

1 个答案:

答案 0 :(得分:1)

这是一个小例子:

from Tkinter import Tk, Label, Button

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        self.dict_ = {"button_1": "value of button 1", "button_2": "value of button 2", "button_3": "value of button 3"}


        self.button_1 = Button(master, text="button_1", command=lambda: self.OnButtonClick("button_1"))
        self.button_1.pack()

        self.button_2 = Button(master, text="button_2", command=lambda: self.OnButtonClick("button_2"))
        self.button_2.pack()

        self.button_3 = Button(master, text="button_3", command=lambda: self.OnButtonClick("button_3"))
        self.button_3.pack()

    def OnButtonClick(self, btn):
        print(self.dict_[btn])

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

输出:

button_2单击了

enter image description here