在tkinter中单击按钮后,一种返回按钮文本的方法 [英] Working on a way to return the text of a button after the button is clicked in tkinter

查看:439
本文介绍了在tkinter中单击按钮后,一种返回按钮文本的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建使用此lambda函数单击的按钮列表:

I'm trying to create a list of buttons that are clicked with this lambda function:

button1.config(command=(lambda x: (clicked.append(x)))(button1.cget("text")))

这似乎可以解决问题,但是它会立即打印按钮文本,即不等待用户单击按钮。

It seems to sort of work but it prints the button text immediately i.e. it doesn't wait for user to click the button.

关于如何使其响应按钮单击的任何想法?

Any ideas on how to make it responsive to the button click?

class GraphicsInterface:

    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        clicked=[]
        button1 = Button(self.window, text="Dice 1", width=13)
        button1.place(x=60, y=160)

        button1.config(command=(lambda x: (clicked.append(x)))(button1.cget("text")))

        print(clicked)


推荐答案

尝试在lambda中完成所有这些操作是错误的方法。简直太令人困惑了,即使不是不可能做您想做的事情。相反,创建一个可以完成工作的方法,并仅将lambda用作调用该函数的方式:

Trying to do all this in a lambda is the wrong approach. It's simply too confusing, if not impossible to do what you want. Instead, create a method that does the work, and use lambda only as a way to call that function:

from Tkinter import *
class GraphicsInterface:

    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        self.clicked=[]
        button1 = Button(self.window, text="Dice 1", width=13)
        button2 = Button(self.window, text="Dice 2", width=13)
        button1.pack()
        button2.pack()

        button1.configure(command=lambda btn=button1: self.OnClick(btn))
        button2.configure(command=lambda btn=button2: self.OnClick(btn))

        self.window.mainloop()

    def OnClick(self, btn):
        text = btn.cget("text")
        self.clicked.append(text)
        print "clicked:", self.clicked

app = GraphicsInterface()

这篇关于在tkinter中单击按钮后,一种返回按钮文本的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆