philipmrz
philipmrz

Reputation: 41

How do I show a variable in Text() in PySimpleGui

How do I update the sg.Text() in event "choose" to show the variable randomchoice?

This script basically has to chose a random element from the list numbers and then print it.

import random
import PySimpleGUI as sg

numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

layout = [[sg.Text("Rnadom Choice 1-9")],
          [sg.Button("Choose")],
          [sg.Text("Random Choice is:")],
          [sg.Text("randomchoice here")]]

window = sg.Window("Random Chooser", layout, margins=(50, 25))

while True:
    event, values = window.read()
    # End program if user closes window or
    # presses the OK button
    if event == sg.WIN_CLOSED:
        break

    if event == "Choose":
        randomchoice = random.choice(numbers)
        print(randomchoice)

window.close()

Upvotes: 1

Views: 2370

Answers (1)

philipmrz
philipmrz

Reputation: 41

Ok found it out myself its pretty simple:

import random
import PySimpleGUI as sg

numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

layout = [[sg.Text("Random Choice 1-9")],
          [sg.Button("Choose")],
          [sg.Text("Random Choice is:")],
          [sg.Text("", key='-TEXT-')]]

window = sg.Window("Random Chooser", layout, margins=(15, 5))

while True:
    event, values = window.read()
    # End program if user closes window or
    # presses the OK button
    if event == sg.WIN_CLOSED:
        break

    if event == "Choose":
        randomchoice = random.choice(numbers)
        print(randomchoice)
        window['-TEXT-'].update(randomchoice)
window.close()

I just had to add the following things to the code: First of all u have to assign a key to the element u want to update. In my chase -TEXT- to sg.Text(). After that u can use this key to identify the element u want to update using this line:

window['-TEXT-'].update(randomchoice)

You simply chose the element u want to update by the key u set before. After that u can use the method .update() to update the content of this element. This can be a string by using "foo" or a variable just by writing its name into the brackets.

Upvotes: 1

Related Questions