python输入文字点击按钮_Python tkinter如何从按钮中获取文本我点击

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

你想在你的命令中使用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()

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

YdnKP.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值