Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

python - Working on a way to return the text of a button after the button is clicked in tkinter

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way would be to bind the button click event to a function which appends the text to your clicked list. For example,

    self.clicked=[]

    self.button1 = Button(self.window, text="Dice 1", width=13)
    self.button1.place(x=60, y=160)
    self.button1.bind("<Button-1>",self.callback)


def callback(self,event):
    self.clicked.append(event.widget.cget("text"))

You could then add other buttons that also call callback, and get their text through the event parameter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...