2017-06-07 157 views
0

我有这样的代码(只是代码的一部分)。当有人点击列表中名为buttonList的按钮时,我需要按钮文本。 这是我如何使这些按钮呈现的代码。它通常在课堂上我只把代码的主要部分放在这里。 那么我怎么才能点击他按钮上的文字?Python tkinter如何从按钮中获取文本我点击

def obsahOkna(self): 

    #vykresleni 
    radek = 0 
    bunka = 0 
    for i in range(100): 
     btn = Button(self.okno, text=seznamTextu[i], width="5", height="2", bg="black", command=self.getText) 
     btn.grid(row=radek, column=bunka) 

     bunka += 1 
     if bunka == 10 : 
      bunka = 0 
      radek +=1 

def getText(self, udalost): 
    pass 
+1

欢迎来到StackOverflow!请阅读[如何提出一个好问题](https://stackoverflow.com/help/how-to-ask)。正确提问可以帮助你获得更好的答案,并帮助他人了解你的问题,如果他们有类似的问题。另请提供[MCVE](https://stackoverflow.com/help/mcve)。这将使我们能够帮助你解决你的问题。 –

+0

我的问题到底有什么不好?我添加了一些代码并描述了我想要的内容 –

+0

首先,你并没有表明你在一个班级工作,而这种改变会产生影响。我认为你是因为你在方法中使用自我,但仍然应该向读者明确。在回答问题时,你真的不想做出假设。 –

回答

0

好的,这里是一个例子,使用一个类来执行我认为它是你问的东西。

你想在你的命令中使用lambda并将文本的值赋给一个变量。然后您将该变量传递给getTest(self, text)方法以便能够打印您的按钮。

从您的评论

整个代码是不需要我只是需要的方式来获得按钮文本没有别的

我创建了一个位的代码来说明你想要什么。

编辑:我已经添加了代码,可以让你改变按钮的配置。

import tkinter as tk 

# created this variable in order to test your code. 
seznamTextu = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th Button"] 

class MyButton(tk.Frame): 
    def __init__(self, parent, *args, **kwargs): 
     tk.Frame.__init__(self, parent, *args, **kwargs) 
     self.parent = parent 
     self.obsahOkna() 
    def obsahOkna(self): 

     radek = 0 
     bunka = 0 
     for i in range(5): 
      btn = tk.Button(self.parent, text=seznamTextu[i]) 
      btn.config(command= lambda t=seznamTextu[i], btn = btn: self.getText(t, btn)) 
      # in order for this to work you need to add the command in the config after the button is created. 
      # in the lambda you need to create the variables to be passed then pass them to the function you want. 
      btn.grid(row=radek, column=bunka) 

      bunka += 1 
      if bunka == 2 : # changed this variable to make it easier to test code. 
       bunka = 0 
       radek +=1 

    def getText(self, text, btn): 
     btn.configure(background = 'black', foreground = "white") 
     print("successfully called getText") 
     print(text) 


if __name__ == "__main__": 
    root = tk.Tk() 
    myApp = MyButton(root) 


    root.mainloop() 

这是运行程序并按下几个按钮的结果。

enter image description here

相关问题