comment a line of code if checkbox checked Pysimplegui - python

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

Related

how to return value inside a dictionary which is changed by a radio button

I created a dictionary with two keys, when selecting one of the keys, the dictionary items are updated, the problem is that I am not returning the selected value within the updated list.
for example, when selecting 'male', and then 'Executed', I would like to receive 'Executed' as a value
import PySimpleGUI as sg
genero = {
'male': ['Required','Executed'],
'female': ['Required', 'Performed']
}
layout = [
[sg.Radio('male', "RADIO1", default=False, key="-IN1-")],
[sg.Radio('female', "RADIO1", default=False, key="-IN2-")],
[sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')],
[sg.Push(),sg.Button('GENERATE'), sg.Exit("Exit")]
]
window = sg.Window("GENERATE PETITION", layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Exit":
break
elif values["-IN1-"] == True:
window['-PART-'].update(genero['male'])
elif values["-IN2-"] == True:
window['-PART-'].update(genero['female'])
elif event == 'GENERATE':
print('-PART-')
window.close()
print(event,values)
atualmente está retornando assim: Exit {'-IN1-': True, '-IN2-': False, '-PART-': []}
There's programming logic issue in the event loop, it will be better for all the cases starts with the event decision, not the value(s) decision. In your code, the case for the event GENERATE will be never executed after any one of the Radio element clicked.
import PySimpleGUI as sg
genero = {
'male': ['Required','Executed'],
'female': ['Required', 'Performed']
}
layout = [
[sg.Radio('male', "RADIO1", default=False, enable_events=True, key="-IN1-")],
[sg.Radio('female', "RADIO1", default=False, enable_events=True, key="-IN2-")],
[sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')],
[sg.Push(),sg.Button('GENERATE'), sg.Exit("Exit")]
]
window = sg.Window("GENERATE PETITION", layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Exit":
break
elif event in ('-IN1-', '-IN2-'):
if values["-IN1-"] == True:
window['-PART-'].update(genero['male'])
else:
window['-PART-'].update(genero['female'])
elif event == 'GENERATE':
selections = values['-PART-']
if selections:
print(selections[0])
else:
print('Nothing selected !')
window.close()

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

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

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

Using 'esc' to close PySimpleGUI window

I have a PySimpleGUI window that I want to maximise, eventually without a title bar. I want to use the 'esc' key to close the window.
Here's my (simplified) code:
import msvcrt
import PySimpleGUI as sg
layout = [[sg.Text(size=(40, 1), font=("Arial", (32)), justification='left', key='-TEXT-')]]
window = sg.Window(title="Window", layout=layout, grab_anywhere=True, finalize = True, no_titlebar=False)
window.maximize()
escape = False
while True:
event, values = window.read()
if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
escape = True
else:
ecape = False
if event == sg.WIN_CLOSED or event == 'Cancel' or escape == True:
break
window.close()
The close button works fine - but pressing escape does nothing.
I've tried several of the answers here, but with no luck.
What's going wrong, and how can I fix it?
Bind event "<Escape>" to window to generate an event,
import PySimpleGUI as sg
layout = [[sg.Text(size=(40, 1), font=("Arial", (32)), justification='left', key='-TEXT-')]]
window = sg.Window(title="Window", layout=layout, grab_anywhere=True, finalize = True, no_titlebar=False)
window.maximize()
window.bind("<Escape>", "-ESCAPE-")
while True:
event, values = window.read()
if event in (sg.WINDOW_CLOSED, "-ESCAPE-"):
break
print(event, values)
window.close()
Solved.
As #knosmos pointed out, getch is only for the command line. Adding return_keyboard_events=True and event == 'Escape:27' did the trick.

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