how to restart the code so that it starts again from scratch? - python

the code receives some inputs, and I also have some functions to check the inputs, if they are wrong, I would like the program to restart so that it asks the user again to type correctly, however, without a break, the code continues to the next input
window1, window2 = infos_window(), None # Using PySimpleGUI to create GUI
while True:
window, events, values = sg.read_all_windows()
if window == window1 and events == sg.WIN_CLOSED:
break
if window == window2 and events == sg.WIN_CLOSED:
break
if window == window1 and events == 'Continue':
window1_values = values
try:
url_check(window1_values)
except ValueError:
break
window1.hide()
window2 = price_input()
if window == window2 and events == 'Send':
window2_values = values
try:
check_price(window2_values)
except ValueError:
break

maybe like this not completely sure tho
main():
while True:
window, events, values = sg.read_all_windows()
if window == window1 and events == sg.WIN_CLOSED:
time.sleep(1)
main()
if window == window2 and events == sg.WIN_CLOSED:
time.sleep(1)
main()
if window == window1 and events == 'Continue':
window1_values = values
try:
url_check(window1_values)
except ValueError:
time.sleep(1)
main()
window1.hide()
window2 = price_input()
if window == window2 and events == 'Send':
window2_values = values
try:
check_price(window2_values)
except ValueError:
time.sleep(1)
main()

It is not necessary for multi-windows here, just call sub window in main window.
You can find that almost same code in both windows
import PySimpleGUI as sg
def sub_window():
sg.theme('DarkBlue4')
layout = [
[sg.Text("Value 2"), sg.Input("", do_not_clear=False, key="INPUT")],
[sg.Button('Send'), sg.Button('Exit')],
]
window = sg.Window('Title', layout, modal=True, finalize=True)
window['INPUT'].set_focus()
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
value = None
break
elif event == 'Send':
try:
value = int(values["INPUT"])
except ValueError:
continue
break
window.close()
return value
layout = [
[sg.Text("Value 1"), sg.Input("", do_not_clear=False, key="INPUT")],
[sg.Button('Continue'), sg.Button('Exit')],
]
window = sg.Window('Title', layout)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == 'Continue':
try:
value1 = int(values["INPUT"])
except ValueError:
continue
value2 = sub_window()
if value2 is not None:
print(value1, value2)
window.close()

You can put all the code inside a function and then use it whenever you want to restart everything. For example, I use main()
main():
window1, window2 = infos_window(), None # Using PySimpleGUI to create GUI
while True:
window, events, values = sg.read_all_windows()
if window == window1 and events == sg.WIN_CLOSED:
break
if window == window2 and events == sg.WIN_CLOSED:
break
if window == window1 and events == 'Continue':
window1_values = values
try:
url_check(window1_values)
except ValueError:
break
window1.hide()
window2 = price_input()
if window == window2 and events == 'Send':
window2_values = values
try:
check_price(window2_values)
except ValueError:
break
main()
main()

Related

Hotkeys in PySimpleGUI

I'd like to write a GUI with PySimpleGUI that can be used entirely by keyboard. Based on the following sample code:
import PySimpleGUI as sg
layout = [[sg.Text("Hello from PySimpleGUI")], [sg.Button(button_text="OK")]]
window = sg.Window("Demo", layout)
while True:
event, values = window.read()
if event == "OK" or event == sg.WIN_CLOSED:
break
window.close()
How can I add a hotkey which I can press using Alt+O to press the OK-Button? The O on the OK-Button should be underlined:
A minimalist working example derived from: https://github.com/PySimpleGUI/PySimpleGUI/issues/4122
import PySimpleGUI as sg
layout = [
[sg.Button("ok", size=(10, 2), key='button1'),
sg.Button("exit", size=(10, 2), key='button2')],
]
window = sg.Window('Hotkeys', layout, use_default_focus=False, finalize=True)
button1, button2 = window['button1'], window['button2']
window.bind("<Alt_L><o>", "ALT-o")
window.bind("<Alt_L><x>", "ALT-x")
button1.Widget.configure(underline=0, takefocus=0)
button2.Widget.configure(underline=1, takefocus=0)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event in ("button1", "ALT-o"):
print('OK')
elif event in ("button2", "ALT-x"):
break
window.close()

comment a line of code if checkbox checked Pysimplegui

how can i comment/uncomment a line of code by checking and unchecking a checkbox in python with PySimpleGUI?
also i don't know if i wrote the code in correct way but i'm just trying to comment a line of code by checking the checkbox
any other way to do it is also fix my problem
This is my code
layout = [[sg.Text('Choose Options'))],
[sg.Checkbox('Save Posts',key="save-ed")],
[sg.Submit('Next')) ,sg.Cancel("Cancel"))] ]
window = sg.Window('my bot', layout, icon="logo.ico")
event, values = window.read()
window.close()
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Cancel":
break
elif values['save-ed'] == True:
save_input = ['usersave']
elif values['save-ed'] == False:
save_input = ['#usersave']
and this is the code which i want to comment or uncomment with checkbox
try:
save_input = webdriver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[3]/section[1]/span[4]/div/div/button/div')
save_input.click()
sleep(randint(4,5))
except NoSuchElementException:
pass
Following code show how to stop a thread to update time by a checkbox.
from datetime import datetime
from time import sleep
import threading
import PySimpleGUI as sg
def clock(window):
now = None
while timer:
new = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if new != now:
now = new
if flag:
window.write_event_value('CLOCK', now)
sleep(0.1)
sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 16))
layout = [
[sg.Text("", size=(0, 1), key='TIME')],
[sg.Checkbox("Time ON", default=True, enable_events=True, key='TIME ON')],
]
window = sg.Window('Title', layout, finalize=True)
timer, flag = True, True
threading.Thread(target=clock, args=(window,), daemon=True).start()
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
timer = False
break
elif event == 'TIME ON':
flag = values[event]
elif event == 'CLOCK':
window['TIME'].update(values[event])
window.close()
according to previous comment and answer by #jason-yang
i got the point and changed the code like this and fixed my problem
layout = [[sg.Text('Choose Options'))],
[sg.Checkbox('Save Posts',key="save-ed")],
[sg.Submit('Next')) ,sg.Cancel("Cancel"))] ]
window = sg.Window('my bot', layout, icon="logo.ico")
event, values = window.read()
window.close()
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Cancel":
break
if event == "save posts":
if values['save-ed'] == True:
save_input = values['usersave']
elif values['save-ed'] == False:
save_input = values['#usersave']
the rest of the code seems to be correct and i leave it unchanged
try:
save_input = webdriver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[3]/section[1]/span[4]/div/div/button/div')
save_input.click()
sleep(randint(4,5))
except NoSuchElementException:
pass

How do I respond to window resize in PySimpleGUI

How can I get notified when the window is resized in PySimpleGUI?
I have a window that enables resize events, but I'm not finding a way to move the elements around when that resize occurs, so my window renames top left centered the same size when the window changes size.
Here is the basic code:
import PySimpleGUI as sg
layout = [[sg.Button('Save')]]
window = sg.Window('Window Title',
layout,
default_element_size=(12, 1),
resizable=True) # this is the change
while True:
event, values = window.read()
if event == 'Save':
print('clicked save')
if event == sg.WIN_MAXIMIZED: # I just made this up, and it does not work. :)
window.maximize()
if event == sg.WIN_CLOSED:
break
Adding tkinter events to windows results in callback on change of windows size
import PySimpleGUI as sg
layout = [[sg.Button('Save')]]
window = sg.Window('Window Title',
layout,
default_element_size=(12, 1),
resizable=True,finalize=True) # this is the chang
window.bind('<Configure>',"Event")
while True:
event, values = window.read()
if event == 'Save':
print('clicked save')
if event == "Event":
print(window.size)
if event == sg.WIN_CLOSED:
print("I am done")
break
You need to bind "<Configure>" event to check zoomed event.
import PySimpleGUI as sg
layout = [[sg.Text('Window normal', size=(30, 1), key='Status')]]
window = sg.Window('Title', layout, resizable=True, finalize=True)
window.bind('<Configure>', "Configure")
status = window['Status']
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == 'Configure':
if window.TKroot.state() == 'zoomed':
status.update(value='Window zoomed and maximized !')
else:
status.update(value='Window normal')
window.close()

How to resize sg.window in PYsimpleGUI?

I am using PYsimpleGUI in my python code, and while using the window element to create the main window, this is my code.
My code:
import PySimpleGUI as sg
layout = [ [sg.Button('Close')] ]
window = sg.Window('This is a long heading.', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Close':
break
break
window.close()
I notice that when I run this program, the full heading is not shown as the window resizes itself and becomes small.
Is there a way to resize sg.window?
You can add size argument in the sg.Window.
Try this :
import PySimpleGUI as sg
layout = [ [sg.Button('Close')] ]
window = sg.Window('This is a long heading.', layout,size=(290, 50))
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Close':
break
break
window.close()

Is there someone who knows to deal with Wolfram Alpha and Python?

below is my script:
import wolframalpha
client = wolframalpha.Client("LXP5A5-62XJKEY85U")
import PySimpleGUI as sg
sg.theme('DarkPurple') # Add a touch of color
# All the stuff inside your window.
layout = [ [sg.Text('Enter a command'), sg.InputText()],
[sg.Button('Ok'), sg.Button('Cancel')] ]
# Create the Window
window = sg.Window('Sunia', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
res = client.query(values[0])
try:
print (next(res.results).text)
except:
print ("No results")
window.close()
and here is my error:
res = client.query(values[0])
File "C:\Users\jonathan b\AppData\Local\Programs\Python\Python38-32\lib\site-packages\wolframalpha\__init__.py", line 68, in query
assert resp.headers.gettype() == 'text/xml'
AttributeError: 'HTTPMessage' object has no attribute 'gettype'
I think i understand the error which you are getting its very simple you just have to put the
client = wolframalpha.Client("LXP5A5-62XJKEY85U") before sg.theme('DarkPurple')
import wolframalpha
import PySimpleGUI as sg
client = wolframalpha.Client("LXP5A5-62XJKEY85U")
sg.theme('DarkPurple') # Add a touch of color
# All the stuff inside your window.
layout = [ [sg.Text('Enter a command'), sg.InputText()],
[sg.Button('Ok'), sg.Button('Cancel')] ]
# Create the Window
window = sg.Window('Sunia', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
res = client.query(values[0])
try:
print (next(res.results).text)
except:
print ("No results")
window.close()

Categories