[英]How to change text when a button is pressed with PySimpleGUI
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.我正在尝试用 PySimpleGUI 制作一个计算器作为学校项目,我已经用它制作了一个基本的 GUI,但我正在努力使按钮发挥作用。 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我尝试将一个文本元素设置为一个变量,我认为当我按下一个按钮时它会更新但是这似乎没有用,我不确定我做错了什么
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]
.变量buttonX
只是一个变量,与 GUI 无关,您必须调用elemet.update(value=something)
,其中元素可以通过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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.