In my code, Im trying to make a calculator. So there is a 1 button which when pressed, updates the Question: text by adding 1 to it's text. So when I press 1, the text will convert from Question: to Question: 1. But its not updating. I have faced this problem before too. I think when I do the .update, it will only update the value till its the same number of letters as the text already has. If it has 2 letters and I try to .update('123'), it will only update to 12. Is there any way to get around this???
import PySimpleGUI as sg
layout = [
[sg.Text('Question: ', key='-IN-')],
[sg.Text('Answer will be shown here', key='-OUT-')],
[sg.Button('1'), sg.Button('2'), sg.Button('3')],
[sg.Button('4'), sg.Button('5'), sg.Button('6')],
[sg.Button('7'), sg.Button('8'), sg.Button('9')],
[sg.Button('Enter'), sg.Button('Exit')]
]
window = sg.Window('calculator', layout)
while True:
event, values = window.read()
if event is None or event == 'Exit':
break
elif event == '1':
bleh = window['-IN-'].get()
teh = f'{bleh}1'
window['-IN-'].update(value=teh)
window.close()
As above comment, Example like this,
import PySimpleGUI as sg
layout = [
[sg.InputText('Question: ', readonly=True, key='-IN-')],
[sg.Text('Answer will be shown here', key='-OUT-')],
[sg.Button('1'), sg.Button('2'), sg.Button('3')],
[sg.Button('4'), sg.Button('5'), sg.Button('6')],
[sg.Button('7'), sg.Button('8'), sg.Button('9')],
[sg.Button('Enter'), sg.Button('Exit')]
]
window = sg.Window('calculator', layout)
input = window['-IN-']
while True:
event, values = window.read()
if event is None or event == 'Exit':
break
elif event in '1234567890':
bleh = window['-IN-'].get()
teh = f'{bleh}{event}'
input.update(value=teh)
input.Widget.xview("end") # view end if text is too long to fit element
window.close()
Related
I have a project where I'm trying to build a simple time-clock using Python 3 on a Raspberry Pi. The Pi is running 64-bit Bullseye.
In my script, I create a window with two columns, one for entry and one for display. The entry side is working (as far as I have gone). The display side sorta works, and this is the issue.
The user will enter their code, press "Enter" to see their information, and then press "In" or "Out" for clocking in or out. When the user presses "In", I want to display a message that says either "Clocked In" or "Already Clocked in".
The issue is that the clocked-in message does not display. The statement that fails is the msg_elem.Update( .... If I run the Python debugger, the message is displayed, but not in "normal" running.
My question is What am I doing wrong?
This is a working example...
import sys, os, platform
import PySimpleGUI as sg
from PIL import Image, ImageTk
from time import sleep
import io
#
# Elements
# create the Elements we want to control outside the form
out_elem = sg.Text('', size=(55, 1), font=('Helvetica', 18), text_color='black',justification='center')
in_elem = sg.Input(size=(10,1), do_not_clear=True)
img_elem = sg.Image(size=(240,240),key="-IMAGE-")
msg_elem = sg.Text('', size=(65, 1), font=('Helvetica', 18), text_color='black',justification='center',key='-MSG-')
#
# Columns
button_column = [
[sg.Text("User Input"),in_elem],
[sg.ReadFormButton('1', size=(3,3)),
sg.ReadFormButton('2', size=(3,3)),
sg.ReadFormButton('3', size=(3,3)),
sg.ReadFormButton('Clear', size=(6,3))],
[sg.ReadFormButton('4', size=(3,3)),
sg.ReadFormButton('5', size=(3,3)),
sg.ReadFormButton('6', size=(3,3)),
sg.ReadFormButton('Enter', size=(6,3))],
[sg.ReadFormButton('7', size=(3,3)),
sg.ReadFormButton('8', size=(3,3)),
sg.ReadFormButton('9', size=(3,3)),
sg.ReadFormButton('Quit', size=(6,3))],
[sg.T(''), sg.T(' ' * 8),
sg.ReadFormButton('0', size=(3,3))],
[sg.T('')],
[sg.ReadFormButton('In', size=(13,3)),
sg.ReadFormButton('Out', size=(13,3)),]
]
display_column = [
[sg.Text("User Details")],
[out_elem],
[sg.T(' ' * 30), img_elem],
[msg_elem],
]
#
layout = [
[sg.Column(button_column),
sg.VSeperator(),
sg.Column(display_column,justification='center',vertical_alignment='top')]
]
form = sg.Window('Time Clock', layout, auto_size_buttons=False, size=(800,480))
keys_entered = ''
while True:
button, values = form.Read()
if button is None:
form["-IMAGE-"].update()
out_elem.Update( " " )
break
elif button == 'Clear':
keys_entered = ''
pcpid = ''
empid = ''
form["-IMAGE-"].update()
in_elem.Update(keys_entered)
out_elem.Update( " " )
msg_elem.Update( " " )
elif button in '1234567890':
keys_entered = in_elem.Get()
keys_entered += button
elif button == 'Enter':
keys_entered = '123'
first_name = 'Mike'
last_name = 'Retiredguy'
empid = 12345
im1 = Image.open( 'mike.png' )
im1.thumbnail((240,240))
bio = io.BytesIO()
im1.save( bio, format="PNG")
empimage = bio.getvalue()
form["-IMAGE-"].update( empimage )
dsplAns = f"{empid} - {last_name}, {first_name}"
out_elem.Update( dsplAns )
elif button == 'In':
# import pdb; pdb.set_trace()
sqlAns = 1 # User already clocked in
if sqlAns > 0:
msg_elem.Update( "...is already clocked in! (A)" ) # <=== THIS IS WHAT FAILS
else:
msg_elem.Update( "...is clocked in! (B)" ) # <=== THIS IS WHAT FAILS
sleep(10)
# Clear input
keys_entered = ''
pcpid = ''
empid = ''
form["-IMAGE-"].update()
in_elem.Update(keys_entered)
out_elem.Update( " " )
msg_elem.Update( " " )
elif button == 'Quit':
sys.exit(0)
in_elem.Update(keys_entered)
#
# ###EOF###
I have tried this on the RPi, and on a Virtual system with Debian (not Pi) linux. Both give me the same result. I've searched here on Stack Overflow, and Google in general, and I think I'm doing it correctly, but failing.
The method msg_elem.Update just update the architecture of PySimpleGUI, not the GUI. Need to call window.refresh() before sleep(10) if you want the GUI updated immediately, not until back to window.read(). sleep(10) take long time for GUI to wait, so it will show "Not Responding".
Demo Code
from time import sleep
import threading
import PySimpleGUI as sg
def func(window, value):
global running
message = f'You clicked the button "{value}", this message will be cleared after 3s !'
window.write_event_value('Update', message)
sleep(3)
window.write_event_value('Update', '')
running = False
sg.set_options(font=('Courier New', 12))
layout = [
[sg.Button('Hello'), sg.Button('World')],
[sg.Text('', size=80, key='State')],
]
window = sg.Window('Title', layout)
running = False
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event in ('Hello', 'World') and not running:
running = True
threading.Thread(target=func, args=(window, event), daemon=True).start()
elif event == 'Update':
message = values[event]
window['State'].update(message)
window.close()
i have written the right code in python simple gui, but after running the code, only one row is displayed and the whole table is not shown i dont know why.this is what is displayed after running the code.
import PySimpleGUI as sg
rows=[
["CULTUS","4","3500","300","550"],
["SONATA","3","5000","350","750"],
["KIA Sportage","3","6000","500","700"],
["Yaris","5","4000","300","600"],
["HONDA CIVIC","5","5500","300","600"],
["Pajero","2","7000","500","700"]
]
header =[
["Model", "Available", "Price/Day","Liability Insurance/Day", "Comprehensive Insurance/Day"]
]
layout=[[sg.Table(
values=rows,
headings=header,
size=(500,300),
key="-TABLE-",)
],
[sg.OK(),sg.Cancel()]
]
window = sg.Window('TG Enterprises', layout ,size=(600,400))
event, values = window.read()
if event == 'Cancel':
window.close()
print(event,values)
this is my code ,can anyone please help me what is wrong with this code and what can i do to make it right?
I cut out some of the text to make it easier to comprehend, but basically it turns out that your attempt was very close.
The main error was the header was a list containing a list. whereas it should just have been a list.
so using boilerplate i made a working example for you like this:
import PySimpleGUI as sg
rows=[
["CULTUS","4","3500","300","550"],
["SONATA","3","5000","350","750"],
["KIA Sportage","3","6000","500","700"],
["Yaris","5","4000","300","600"],
["HONDA CIVIC","5","5500","300","600"],
["Pajero","2","7000","500","700"]
]
header =["Model", "Available", "Price","Liability", "Comprehensive"]
layout = [[sg.Text(x) for x in header],
[sg.Table(values=rows,
headings=header,
max_col_width=25,
auto_size_columns=True,
justification='right',
alternating_row_color='lightblue',
key='table')],
[sg.Button('Add'), sg.Button('Delete')]]
window = sg.Window('Table example').Layout(layout)
while True:
event, values = window.Read()
if event is None:
break
print(event, values)
window.Close()
and the result looks like this:
note: I didnt try out the buttons or any other logic. I just provided an example of the correct formatting example.
I am new to PySimpleGui and wonder if the following concept can be applied.
I have to work with two scripts, one related to a GUI and a second one that it is a "Do Something Script".
I am interested in printing the status of an external loop in a window of my GUI Script
The GUIScript that I have coded as an example is the following:
import PySimpleGUI as sg
import MainScript
### GUI Script ###
layout = [
[sg.Text('My text 1 is: '), sg.Text('{}'.format('foo1'), key='-text1-')],
[sg.Text('My text 2 is: '), sg.Text('{}'.format('foo2'), key='-text2-')],
[sg.Text('Sweep number: '), sg.Text('{}'.format('0'), key='-SWEEP-')],
[sg.ProgressBar(max_value=40, orientation='horizontal', size=(50,20), key='-PRO_BAR-')],
[sg.Button("OK"), sg.Button("Cancel")],
]
window =sg.Window("Progress Bar",layout)
while True:
event, values = window.read()
if event == 'Cancel' or event == sg.WIN_CLOSED:
break
if event == "OK":
for s in range(50):
event, values = window.read(1000)
if event == 'Cancel':
break
window['-PRO_BAR-'].update(s+1)
window['-text1-'].update('my new text1')
window['-text2-'].update('my new text2')
window['-SWEEP-'].update(s)
window.refresh()
window.close()
The previous script works as "what I would like to have". I mean that the window['-PRO_BAR-'].update(s+1) and window['-SWEEP-'].update(s) update according to the s value of its own for-loop.
However, I would like to pick up the variable=i from the MainScript (which is the following), and use it back in the GUIScript.
##### MainScript ####
SWEEPS = 50
SWEEPS_LEN = list(range(1, SWEEPS+1))
for i in enumerate(SWEEPS_LEN):
print('sweep: {}'.format(i))
# Do something
# Save Data
Here, it is obvious that i=0, i=1, i=2.... I want to use these variables (that change in the loop) them as:
window['-PRO_BAR-'].update(i+1) and window['-SWEEP-'].update(i), such as the values update.
The GUIScript would show:
Sweep: 1
then i=2, updates and shows
Sweep: 2
then updates and...
Thanks.
I use hide_row() element or feature in my code to hide row but it work only one time when i connected to Retreat button or Retreat key, when i clicked again or in the 2nd time it's not work (see the code or try it to understand what i mean) how make it work continuously not only one time or is there another way to undo or delete section or row.
import PySimpleGUI as sg
layout = [
[sg.Col([[sg.T('Enter your name:'),sg.In()],[sg.Btn('Ok'), sg.Btn('Exit'),
sg.Btn('Add new row')]],k='col_key')]
]
window = sg.Window('Test', layout)
while True:
event, values = window.read()
if event in ('Exit' ,sg.WIN_CLOSED):
break
if event == ('Add new row'):
window.extend_layout(window['col_key'],[[sg.T('Enter your name:', key='new_raw'),(sg.In())]])
window.extend_layout(window['col_key'],[[sg.Btn('Retreat', key='re')]])
if event == ('re'):
window['new_raw'].hide_row()
window['re'].hide_row()
window.close()
It is caused by new element with duplicate key when add new row again, so it wll always find the first element when you call window[new_key].
Should use different key for different element when you create a new element.
Key of new element will be replace by
element.Key = str(element.Key) + str(self.UniqueKeyCounter)
So key for new elements will be
'new_raw', 're', 'new_raw0', 're1', 'new_raw2', 're3', 'new_raw4', 're5', ...
you can check it by
>>> window.key_dict
{
...
'new_raw': <PySimpleGUI.PySimpleGUI.Text object at 0x000001D3A5B80FA0>,
'new_raw0': <PySimpleGUI.PySimpleGUI.Text object at 0x000001D3A6FA1280>,
'new_raw2': <PySimpleGUI.PySimpleGUI.Text object at 0x000001D3A6FA1220>,
're': <PySimpleGUI.PySimpleGUI.Button object at 0x000001D3A6FA1CD0>,
're1': <PySimpleGUI.PySimpleGUI.Button object at 0x000001D3A6FA1340>,
're3': <PySimpleGUI.PySimpleGUI.Button object at 0x000001D3A6FA11F0>}
After new row generated, the key of button Retreat is not 're', but starts with 're' and ends with an index.
Update code as following
import PySimpleGUI as sg
layout = [
[sg.Col([[sg.T('Enter your name:'),sg.In()],[sg.Btn('Ok'), sg.Btn('Exit'),
sg.Btn('Add new row')]],k='col_key')]
]
window = sg.Window('Test', layout)
index = 0
while True:
event, values = window.read()
if event in ('Exit' ,sg.WIN_CLOSED):
break
if event == ('Add new row'):
window.extend_layout(window['col_key'],[[sg.T('Enter your name:', key=f'new_raw {index}'),(sg.In(key=f'input {index}'))]])
window.extend_layout(window['col_key'],[[sg.Btn('Retreat', key=f're {index}')]])
index += 1
if event.startswith('re'):
i = event.split(' ')[-1]
window[f'new_raw {i}'].hide_row()
window[f're {i}'].hide_row()
window.close()
There's still problem for old rows hidden will still be kept in memory, so occupied memory will grow higher and higher if you add new row again and again, but it's not question to be discussed here.
First, I have read the docs. I understand that the information is stored in Key= x. My issue is when I call a function from another file it does not recognize x.
I have read the docs, but failing to understand how to use the key
I tried putting x into a variable and passing it to the function.
File 1
def add_details():
today1 = date.today()
today2 = today1.strftime("%Y/%m/%d")
create = str(today2)
name = str(_name_)
reason = str(_reason_)
startDate = str(_startDate_)
endDate = str(_endDate_)
add_data(create,name,reason,startDate, endDate)
def add_data(create,name,reason,startDate, endDate):
engine.execute('INSERT INTO schedule(Created_On, Fullname, reason, Start_Date, End_Date ) VALUES (?,?,?,?,?)',(create,name,reason,startDate,endDate))
File 2
while True:
event, values = window.Read()
print(event, values)
if event in (None, 'Exit'):
break
if event == '_subdate_': #subdate is the button Submit
sf.add_details()
My expected results are that the inputs of the GUI are passed to the function, then off to a SQLite db.
Error: name 'name' not defined
(or any key variable)
This is an example that you'll find running on Trinket (https://pysimplegui.trinket.io/demo-programs#/demo-programs/design-pattern-2-persistent-window-with-updates)
It shows how keys are defined in elements and used after a read call.
import PySimpleGUI as sg
"""
DESIGN PATTERN 2 - Multi-read window. Reads and updates fields in a window
"""
# 1- the layout
layout = [[sg.Text('Your typed chars appear here:'), sg.Text(size=(15,1), key='-OUTPUT-')],
[sg.Input(key='-IN-')],
[sg.Button('Show'), sg.Button('Exit')]]
# 2 - the window
window = sg.Window('Pattern 2', layout)
# 3 - the event loop
while True:
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
break
if event == 'Show':
# Update the "output" text element to be the value of "input" element
window['-OUTPUT-'].update(values['-IN-'])
# In older code you'll find it written using FindElement or Element
# window.FindElement('-OUTPUT-').Update(values['-IN-'])
# A shortened version of this update can be written without the ".Update"
# window['-OUTPUT-'](values['-IN-'])
# 4 - the close
window.close()