python 如何使用PySimpleGUI在按下按钮时更改文本

r1zk6ea1  于 2023-02-21  发布在  Python
关注(0)|答案(1)|浏览(409)

我尝试用PySimpleGUI做一个计算器,作为一个学校项目,我已经用它做了一个基本的GUI,但我很难使按钮的功能。

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()

我尝试将文本元素设置为变量,我认为当我按下按钮时会更新,但似乎不起作用,不确定我做错了什么

qxsslcnc

qxsslcnc1#

变量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()

相关问题