I'm trying to make a calculator with PySimpleGUI as a school project and I have made a basic GUI with it but I am struggling to make the buttons functional. I made functions for all the buttons.
import PySimpleGUI as sg
def pressed_button_0():
button0 = 0
def pressed_button_1():
button1 = 1
def pressed_button_2():
button2 = 2
def pressed_button_3():
button3 = 3
def pressed_button_4():
button4 = 4
def pressed_button_5():
button5 = 5
def pressed_button_6():
button6 = 6
def pressed_button_7():
button7 = 7
def pressed_button_8():
button8 = 8
def pressed_button_9():
button9 = 9
problem = ''
layout_1 = [
[sg.Text('Calculator')],
[sg.Text(str(problem))],
[sg.Button('1'), sg.Button('2'), sg.Button('3'), sg.Button('÷')],
[sg.Button('4'), sg.Button('5'), sg.Button('6'), sg.Button('×')],
[sg.Button('7'), sg.Button('8'), sg.Button('9'), sg.Button(' ')],
[sg.Button('.'), sg.Button('0'), sg.Button('='), sg.Button('-')]
]
sg.theme('dark grey 13')
window = sg.Window('Calculator', layout_1)
problem = ''
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
if event == '0':
pressed_button_0()
window.close()
i tried setting a text element as a variable which i thought would update when i pressed a button but that didnt seem to work, not sure what i did wrong
CodePudding user response:
Variable buttonX
is just a variable and nothing about the GUI, you have to call elemet.update(value=something)
where the element can be found by window[element_key]
.
import PySimpleGUI as sg
keys = ['123÷', '456×', '789 ', '.0=-']
all_keys = ''.join(keys)
sg.theme('DarkGrey13')
sg.set_options(font=('Courier New', 16))
layout = [
[sg.Text('Calculator', expand_x=True, justification='center')],
[sg.Input(size=5, expand_x=True, key='-INPUT-')]] [
[sg.Button(key, size=3) for key in row] for row in keys] [
[sg.Push(), sg.Button('Submit')],
]
window = sg.Window('Calculator', layout)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event in all_keys:
problem = values['-INPUT-']
window['-INPUT-'].update(problem event)
window['-INPUT-'].widget.xview_moveto(1)
elif event == 'Submit':
problem = values['-INPUT-']
print(problem)
window.close()