【问题标题】:Tkinter: get value from entry with button and store in variableTkinter: get value from entry with button and store in variable
【发布时间】:2022-12-02 07:49:15
【问题描述】:

Say that we have an entry_object, a button button_object and a global variable called score.

I want to update the score when the button is clicked and the entry has a value. I tried looking at this answer but I need something slightly different. The main difference is the storing of the value in a variable.

I have a function to generate the elements:

def generate_gui():
    root = tk.Tk()
    root.geometry('900x700+50+50')
    entry_object = tk.Entry(root, width=40)
    entry_object.pack()
    button_object = tk.Button(root, text='submit')
    button_object.pack()
    return root, entry_object, button_object

I now want to update score with `entry_object.get()' when the button is clicked.

generate_gui()
while accumulated_score < 10:
    for player in players:
        ** #### pseudocode: if button_object clicked then player.accumulated_score += score#### **

How do I replace the pseudocode with the right code? Please help :)

【问题讨论】:

  • Research for tk.StringVar or IntVar and use the option of text variable. In addition, for GUI code you usually don't use a while loop, since the event loop is driven.
  • You mention several player objects but don't have any player objects in the code you posted. Also, you don't have any sort of widget for displaying a score.

标签: python tkinter


【解决方案1】:

#If score is a global variable then:

score = 0
root = tk.Tk()
root.geometry('900x700+50+50')
entry_object = tk.Entry(root, width=40)
entry_object.pack()

def increment():
    global score
    score += 1

button_object = tk.Button(root, text='submit', command=increment() )
root.mainloop()

#If it's an atribute from an object "player" then:

root = tk.Tk()
root.geometry('900x700+50+50')
entry_object = tk.Entry(root, width=40)
entry_object.pack()

def increment():
   for player in players:
       if player.accumulated_score <= 10:
            player.accumulated_score += score
button_object = tk.Button(root, text='submit', command=increment() )
root.mainloop()

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2022-12-02
    • 1970-01-01
    • 2023-04-01
    • 2021-12-28
    • 2015-10-18
    • 2022-12-02
    • 2022-12-01
    • 2022-12-01
    相关资源
    最近更新 更多