PySimpleGUI:如何使用以下方法将值从字符串转换为浮点数
PySimpleGUI: How do I convert a value from string to float using
我有一个简短的 PySimpleGUI 程序来测试 FocusOut。 Jason Yang 提供的代码完全符合我的要求。但是,出现了一个新问题,因此我将其作为一个新问题发布。
在下面的代码中,如果输入失败并在“FUELQUANT”字段中输入金额,则会引发错误并生成弹出窗口。但是,如果您输入一个值,例如 13.5,我希望它在收件箱中反映为 13.50。为此,我想读取字段中的值,然后将其格式化为小数点后 2 位,并通过 .update 将其 return 发送到收件箱。
我的问题是,一旦我输入格式代码行,如果收件箱中没有值(即当它应该导致弹出窗口激活时),我就会收到错误消息:“无法将字符串转换为浮动:''“有办法解决这个问题吗?我已经尝试了我能找到的所有方法来尝试解决问题,但似乎没有任何效果。
import PySimpleGUI as sg
from tkcalendar import Calendar, DateEntry
import sqlite3
from datetime import date
import time
TodayDt=date.today()
print("Today's date is " + str(TodayDt))
def popup(*args, elem=None):
for element in elements:
element.unbind('<FocusOut>')
window.refresh() # Make unbind effect
layout = [
[sg.Text('\n'.join(args))],
[sg.Button('OK')],
]
sg.Window('Popup', layout).read(close=True)
if elem:
elem.set_focus()
window.refresh() # Make set_focus effect
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
layout=[
[sg.T("Today's date is:"),sg.InputText(TodayDt, size=(10, 10), key='_TODAYCAL_')],
[sg.T("Select new transaction date:"),sg.CalendarButton('Calendar', target='-IN4-', key='_DATE_',format='%Y-%m-%d'),sg.In(key='-IN4-', size=(10,1))],
[sg.T("Fuel quantity (in litres):"),sg.In(key="_FUELQUANT_",size=(10,1),enable_events=True),sg.T("Fuel amount N$:"),sg.In(key="_FUELAMNT_", size=(10,1),enable_events=True)],
[sg.T("Oil quantity (in millilitres:"),sg.In(key="_OILQUANT_",size=(10,1)),sg.T("Oil amount N$:"),sg.In(key="_OILAMNT_",size=(10,1))],
]
window = sg.Window('My Vehicle Logbook', layout, finalize=True)
keys = ('_FUELQUANT_','_FUELAMNT_')
elements = [window[key] for key in keys]
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
elif event.endswith("+FOCUS OUT"):
print(event)
key = event.split('+')[0]
amount=values[key]
print(str(amount))
#amount="{: .2f}".format(float(amount))
# window.find_element(key).update(amount)
print(amount)
if values[key] == '':
popup("Warning", f"Blank entry in {key} is not acceptable !", elem=window[key])
window.close()
是关于编程逻辑的。
它的演示代码
import PySimpleGUI as sg
def popup(*args, elem=None):
for element in elements:
element.unbind('<FocusOut>')
window.refresh() # Make unbind effect
layout = [
[sg.Text('\n'.join(args))],
[sg.Button('OK')],
]
sg.Window('Popup', layout).read(close=True)
if elem:
elem.set_focus()
window.refresh() # Make set_focus effect
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
layout=[[sg.Input(key=f'-IN{i}-')] for i in range(5)]
window = sg.Window('My Vehicle Logbook', layout, finalize=True)
keys = ('-IN1-', '-IN2-')
elements = [window[key] for key in keys]
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
elif event.endswith("+FOCUS OUT"):
key = event.split('+')[0]
try:
number = float(values[key])
string = f'{number:.2f}'
window[key].update(string)
except ValueError:
popup("Warning", "Wrong format for a float number !", elem=window[key])
window.close()
如果切换到其他程序仍然会出现问题,当焦点位于任何绑定输入时,它仍然会生成 FocusOut
事件。在单击一个按钮 submit
后验证所有输入可能更好。
我有一个简短的 PySimpleGUI 程序来测试 FocusOut。 Jason Yang 提供的代码完全符合我的要求。但是,出现了一个新问题,因此我将其作为一个新问题发布。 在下面的代码中,如果输入失败并在“FUELQUANT”字段中输入金额,则会引发错误并生成弹出窗口。但是,如果您输入一个值,例如 13.5,我希望它在收件箱中反映为 13.50。为此,我想读取字段中的值,然后将其格式化为小数点后 2 位,并通过 .update 将其 return 发送到收件箱。 我的问题是,一旦我输入格式代码行,如果收件箱中没有值(即当它应该导致弹出窗口激活时),我就会收到错误消息:“无法将字符串转换为浮动:''“有办法解决这个问题吗?我已经尝试了我能找到的所有方法来尝试解决问题,但似乎没有任何效果。
import PySimpleGUI as sg
from tkcalendar import Calendar, DateEntry
import sqlite3
from datetime import date
import time
TodayDt=date.today()
print("Today's date is " + str(TodayDt))
def popup(*args, elem=None):
for element in elements:
element.unbind('<FocusOut>')
window.refresh() # Make unbind effect
layout = [
[sg.Text('\n'.join(args))],
[sg.Button('OK')],
]
sg.Window('Popup', layout).read(close=True)
if elem:
elem.set_focus()
window.refresh() # Make set_focus effect
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
layout=[
[sg.T("Today's date is:"),sg.InputText(TodayDt, size=(10, 10), key='_TODAYCAL_')],
[sg.T("Select new transaction date:"),sg.CalendarButton('Calendar', target='-IN4-', key='_DATE_',format='%Y-%m-%d'),sg.In(key='-IN4-', size=(10,1))],
[sg.T("Fuel quantity (in litres):"),sg.In(key="_FUELQUANT_",size=(10,1),enable_events=True),sg.T("Fuel amount N$:"),sg.In(key="_FUELAMNT_", size=(10,1),enable_events=True)],
[sg.T("Oil quantity (in millilitres:"),sg.In(key="_OILQUANT_",size=(10,1)),sg.T("Oil amount N$:"),sg.In(key="_OILAMNT_",size=(10,1))],
]
window = sg.Window('My Vehicle Logbook', layout, finalize=True)
keys = ('_FUELQUANT_','_FUELAMNT_')
elements = [window[key] for key in keys]
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
elif event.endswith("+FOCUS OUT"):
print(event)
key = event.split('+')[0]
amount=values[key]
print(str(amount))
#amount="{: .2f}".format(float(amount))
# window.find_element(key).update(amount)
print(amount)
if values[key] == '':
popup("Warning", f"Blank entry in {key} is not acceptable !", elem=window[key])
window.close()
是关于编程逻辑的。
它的演示代码
import PySimpleGUI as sg
def popup(*args, elem=None):
for element in elements:
element.unbind('<FocusOut>')
window.refresh() # Make unbind effect
layout = [
[sg.Text('\n'.join(args))],
[sg.Button('OK')],
]
sg.Window('Popup', layout).read(close=True)
if elem:
elem.set_focus()
window.refresh() # Make set_focus effect
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
layout=[[sg.Input(key=f'-IN{i}-')] for i in range(5)]
window = sg.Window('My Vehicle Logbook', layout, finalize=True)
keys = ('-IN1-', '-IN2-')
elements = [window[key] for key in keys]
for element in elements:
element.bind('<FocusOut>','+FOCUS OUT')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
elif event.endswith("+FOCUS OUT"):
key = event.split('+')[0]
try:
number = float(values[key])
string = f'{number:.2f}'
window[key].update(string)
except ValueError:
popup("Warning", "Wrong format for a float number !", elem=window[key])
window.close()
如果切换到其他程序仍然会出现问题,当焦点位于任何绑定输入时,它仍然会生成 FocusOut
事件。在单击一个按钮 submit
后验证所有输入可能更好。