"KeyError" for PySimpleGUI Project Integration - python

I have been trying to integrate a new page into a project i am doing.
import PySimpleGUI as sg
import os
def page2b():
company_list_column = [
[sg.Text('Pick your company name')],
[sg.Listbox(os.listdir("C:\/FYP\/GUI\/Companies"), size=(25, 5), key='-EC-', enable_events=True)]
]
company_column = [
[sg.Text(size=(40,1), key='-Company Selected-')],
[sg.Text(size=(40,1), key='-Folder Selected-')],
]
layout = [
[sg.Text('Select your Company', justification='center',font=("Arial",22))],
[
sg.Column(company_list_column),
sg.VSeparator(),
sg.Column(company_column),
],
[sg.Button('Select Company'), sg.Button('Close')]
]
return sg.Window('Baseline Analyzer', layout, default_element_size=(100, 1), auto_size_buttons=False,
default_button_element_size=(12, 1), size=(600,270))
window= page2b()
while True: # the event loop
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Close":
break
if values['-EC-']: # if something is highlighted in the list
window['-Company Selected-'].update(f"Company selected: {values['-EC-'][0]}")
window['-Folder Selected-'].update(f"Your folder is: C:\FYP\GUI\Companies\{values['-EC-'][0]}")
if event == "Select Company": #The path of the folder to store the things at
word= {values['-EC-'][0]}
word = "".join(word)
foldername = "C:\FYP\\GUI\\Companies\\" + word
break
window.close()
In summary, this would display a list of company folders for me to choose from and when i click on an folder, i would see what is indeed the selected folder, as exampled in the below screenshot:
As a standalone progam, the above page works absolutely fine. However, the moment i try to integrate it into my main program, as evidenced down below:
from tkinter.constants import UNDERLINE
from tkinter.font import BOLD, ITALIC
import PySimpleGUI as sg
from datetime import datetime, date, time
import time
import csv
import pandas as pd
import os
from stat import S_IREAD, S_IRGRP, S_IROTH
sg.ChangeLookAndFeel('DarkTeal9')
# ------ Menu Definition ------ #
menu_def = [
['Company Selection',['New Company','Existing Company']],
['Help',['How to use']]
]
menu_def2 = [
['Scan Management', ['Start Audit Task']],
['Baseline Management', ['View Baselines'] ],
['Help', ['How to Use']]
]
# ------ Functions Defintion ------ #
def clear_input():
for key in values:
if key != 'Import Host':
window[key]('')
return None
def folder_gen():
clientFolder = os.mkdir(values['New Client Name'])
# ------ GUI Defintion ------ #
def page1():
layout = [
[sg.Menu(menu_def)],
[sg.Text('Welcome to the Baseline Analyzer!', justification='center',font=("Arial",25, BOLD))],
[sg.Button('New Company')],
[sg.Button('Existing Company')],
[sg.Button('Exit')],
]
return sg.Window('Baseline Analyzer', layout,element_justification='c', default_element_size=(100, 1), auto_size_text=False, auto_size_buttons=False,
default_button_element_size=(25, 3), size=(600,270), finalize=True)
def page_2a():
layout = [
[sg.Text('New Company Name: ', size=(20,1)), sg.InputText(key='New Client Name')],
[sg.Text('Date of Registration: ', size=(20,1)), sg.InputText(key='Date')],
[sg.Text('Location of Site: ', size=(20,1)), sg.InputText(key='Location')],
[sg.Text('Department: ', size=(20,1)), sg.InputText(key='Department')],
[sg.Text('Company Liaison Name: ', size=(20,1)), sg.InputText(key='Liaison')],
[sg.Text('Company Liaison Email: ', size=(20,1)), sg.InputText(key='Contact')],
[sg.Text('Company Liaison Number: ', size=(20,1)), sg.InputText(key='Number')],
[sg.Button('Create Company'), sg.Button('Clear'), sg.Exit()]
]
return sg.Window('Generate Client Profile', layout,element_justification='c', default_element_size=(100, 1), auto_size_text=False, auto_size_buttons=False,
default_button_element_size=(12, 1), size=(600,270), finalize=True)
def page2b():
company_list_column = [
[sg.Text('Pick your company name')],
[sg.Listbox(os.listdir("C:\/FYP\/GUI\/Companies"), size=(25, 5), key='-EC-', enable_events=True)]
]
company_column = [
[sg.Text(size=(40,1), key='-Company Selected-')],
[sg.Text(size=(40,1), key='-Folder Selected-')],
]
layout = [
[sg.Text('Select your Company', justification='center',font=("Arial",22))],
[
sg.Column(company_list_column),
sg.VSeparator(),
sg.Column(company_column),
],
[sg.Button('Select Company'), sg.Button('Close')]
]
return sg.Window('Baseline Analyzer', layout, default_element_size=(100, 1), auto_size_buttons=False,
default_button_element_size=(12, 1), size=(600,270), finalize=True)
window1, window2= page1(), None
# ------ Loop & Process button menu choices ------ #
# ------ Process menu choices ------ #
while True:
window, event, values = sg.read_all_windows()
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
if window == window2:
window2 = None
elif window == window1:
break
# Clear New Scan form inputs
elif event == 'Clear':
clear_input()
#Exisiting Company selection page
if event == 'New Company':
window = page_2a()
elif event == 'Existing Company':
window = page2b()
if values['-EC-']: # if something is highlighted in the list
window['-Company Selected-'].update(f"Company selected: {values['-EC-'][0]}")
window['-Folder Selected-'].update(f"Your folder is: C:\FYP\GUI\Companies\{values['-EC-'][0]}")
if event == "Select Company": #The path of the folder to store the things at
word= {values['-EC-'][0]}
word = "".join(word)
foldername = "C:\FYP\\GUI\\Companies\\" + word
window.close()
I am presented with this "keyError" and have been racking my head on how to solve it
Traceback (most recent call last):
File "c:\Users\******\Documents\******\******\testing.py", line 140, in <module>
if values['-EC-']: # if something is highlighted in the list
KeyError: '-EC-'
Is there a solution to my predicament?

Line window = page2b() creates new window but it doesn't update values in window, event, values - it would need to run again sg.read_all_windows()
So you should run if values['-EC-'] directly in while True. But it will be execute for every window so you would have to check if '-EC-' in values and values['-EC-'] or you would have to check if window == window2 but it needs also use window2 = page2b() instead of window = page2b() or even better window2b = page2b() to recognize if you run page2a or page2b
# ---
window1 = page1()
window2a = None
window2b = None
while True:
window, event, values = sg.read_all_windows()
#print('window:', window)
#print('event:', event)
#print('values:', values)
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
if window == window2a:
window2a = None
elif window == window2b:
window2b = None
elif window == window1:
break
elif event == 'Clear':
clear_input()
# - events, values unique for every window -
if window == window1:
if event == 'New Company':
window2a = page_2a()
elif event == 'Existing Company':
window2b = page2b()
elif window == window2a:
# ... code ...
pass
elif window == window2b:
if values['-EC-']:
window['-Company Selected-'].update(f"Company selected: {values['-EC-'][0]}")
window['-Folder Selected-'].update(f"Your folder is: C:\FYP\GUI\Companies\{values['-EC-'][0]}")
if event == "Select Company":
word = {values['-EC-'][0]}
word = "".join(word)
foldername = "C:\FYP\\GUI\\Companies\\" + word
window.close()
Or even
window1 = page1()
window2a = None
window2b = None
while True:
window, event, values = sg.read_all_windows()
#print('window:', window)
#print('event:', event)
#print('values:', values)
if window == window1:
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
break
elif event == 'New Company':
window2a = page_2a()
elif event == 'Existing Company':
window2b = page2b()
elif window == window2a:
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
window2a = None
elif event == 'Clear':
clear_input()
elif window == window2b:
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
window2b = None
elif values['-EC-']:
window['-Company Selected-'].update(f"Company selected: {values['-EC-'][0]}")
window['-Folder Selected-'].update(f"Your folder is: C:\FYP\GUI\Companies\{values['-EC-'][0]}")
elif event == "Select Company":
word = {values['-EC-'][0]}
word = "".join(word)
foldername = "C:\\FYP\\GUI\\Companies\\" + word
EDIT:
Other idea is to create for every window new while-loop but sometimes it may work different then previous version. When window2 is opened then it blocks buttons in window1 so you can't open two windows 2 at the same time. Previous version can open New Company','Existing Company at the same time - it may even open many Existing Company and many 'New Company at the same time. This version can open only one 'New Company or only one Existing Company and it can open New Company','Existing Company at the same time.
And in new version you can't use Exit in window1 when window2 is open.
I changed path in listdir() to run it on my system.
from tkinter.constants import UNDERLINE
from tkinter.font import BOLD, ITALIC
import PySimpleGUI as sg
from datetime import datetime, date, time
import time
import csv
import pandas as pd
import os
from stat import S_IREAD, S_IRGRP, S_IROTH
sg.ChangeLookAndFeel('DarkTeal9')
# ------ Menu Definition ------ #
menu_def = [
['Company Selection',['New Company','Existing Company']],
['Help',['How to use']]
]
menu_def2 = [
['Scan Management', ['Start Audit Task']],
['Baseline Management', ['View Baselines'] ],
['Help', ['How to Use']]
]
# ------ Functions Defintion ------ #
def clear_input():
for key in values:
if key != 'Import Host':
window[key]('')
return None
def folder_gen():
clientFolder = os.mkdir(values['New Client Name'])
# ------ GUI Defintion ------ #
def page1():
layout = [
[sg.Menu(menu_def)],
[sg.Text('Welcome to the Baseline Analyzer!', justification='center',font=("Arial",25, BOLD))],
[sg.Button('New Company')],
[sg.Button('Existing Company')],
[sg.Button('Exit')],
]
window = sg.Window('Baseline Analyzer', layout,element_justification='c', default_element_size=(100, 1), auto_size_text=False, auto_size_buttons=False,
default_button_element_size=(25, 3), size=(600,270), finalize=True)
while True:
event, values = window.read()
#print('window:', window)
#print('event:', event)
#print('values:', values)
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
return
elif event == 'New Company':
page_2a()
elif event == 'Existing Company':
page2b()
def page_2a():
layout = [
[sg.Text('New Company Name: ', size=(20,1)), sg.InputText(key='New Client Name')],
[sg.Text('Date of Registration: ', size=(20,1)), sg.InputText(key='Date')],
[sg.Text('Location of Site: ', size=(20,1)), sg.InputText(key='Location')],
[sg.Text('Department: ', size=(20,1)), sg.InputText(key='Department')],
[sg.Text('Company Liaison Name: ', size=(20,1)), sg.InputText(key='Liaison')],
[sg.Text('Company Liaison Email: ', size=(20,1)), sg.InputText(key='Contact')],
[sg.Text('Company Liaison Number: ', size=(20,1)), sg.InputText(key='Number')],
[sg.Button('Create Company'), sg.Button('Clear'), sg.Exit()]
]
window = sg.Window('Generate Client Profile', layout,element_justification='c', default_element_size=(100, 1), auto_size_text=False, auto_size_buttons=False,
default_button_element_size=(12, 1), size=(600,270), finalize=True)
while True:
event, values = window.read()
#print('window:', window)
#print('event:', event)
#print('values:', values)
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
return
elif event == 'Clear':
clear_input()
def page2b():
company_list_column = [
[sg.Text('Pick your company name')],
[sg.Listbox(os.listdir(), size=(25, 5), key='-EC-', enable_events=True)]
]
company_column = [
[sg.Text(size=(40,1), key='-Company Selected-')],
[sg.Text(size=(40,1), key='-Folder Selected-')],
]
layout = [
[sg.Text('Select your Company', justification='center',font=("Arial",22))],
[
sg.Column(company_list_column),
sg.VSeparator(),
sg.Column(company_column),
],
[sg.Button('Select Company'), sg.Button('Close')]
]
window = sg.Window('Baseline Analyzer', layout, default_element_size=(100, 1), auto_size_buttons=False,
default_button_element_size=(12, 1), size=(600,270), finalize=True)
while True:
event, values = window.read()
#print('window:', window)
#print('event:', event)
#print('values:', values)
if event == sg.WIN_CLOSED or event == 'Exit'or event =='Close':
window.close()
return
elif values['-EC-']:
window['-Company Selected-'].update(f"Company selected: {values['-EC-'][0]}")
window['-Folder Selected-'].update(f"Your folder is: C:\FYP\GUI\Companies\{values['-EC-'][0]}")
if event == "Select Company":
word = {values['-EC-'][0]}
word = "".join(word)
foldername = "C:\\FYP\\GUI\\Companies\\" + word
# --- start ---
page1()

Related

Selenium and pyautogui does not seem to work together

I have script where you write information in pyautogui and it launches a window of selenium. The problem is that when the selenium window is open pyautogui lags to the extent that it is not usable.
I have tried removing all code related to selenium but it seems that just launching the window makes the pyautogui stop working
Here is my current code. Most of the pyautogui stuff was taken from a example at github.
Any help would be appreciated
def start_script(information):
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()
# defines the url
print(information)
#coordinates = pd.read_excel('Companies.xlsx', header=None)
#coordinates = str(coordinates.iloc[0, 0])
coordinates = '67, 67'
url = 'https://www.google.se/maps/search/AB/#' + coordinates + ',12.5z'
# opens the website
driver.get(url)
fail = True
while fail == True:
try:
driver.find_element(
By.XPATH, "//div[#class='VtwTSb']//form[1]").click()
except:
fail == True
else:
fail = False
while True:
pass
def make_window(theme):
sg.theme(theme)
menu_def = [['&Application', ['E&xit']]]
input_layout = [
# [sg.Menu(menu_def, key='-MENU-')],
[sg.Button("Open File")],
[sg.Text('Search (ab, ltd, etc)')],
[sg.Input(key='-INPUT-')],
[sg.Text('Coordinates')],
[sg.Input(key='-INPUT-')],
[sg.Spin([i for i in range(1, 11)], initial_value=10,
k='-SPIN-'), sg.Text('The level of zoom')],
[sg.OptionMenu(values=('Right', 'Left', 'Up'),
k='-Direction-'), sg.Text('Direction')],
[sg.Button('Start'), sg.Button('Skip'), sg.Button('Add')]]
logging_layout = [[sg.Text("Anything printed will display here!")],
[sg.Multiline(size=(60, 15), font='Courier 8', expand_x=True, expand_y=True, write_only=True,
reroute_stdout=True, reroute_stderr=True, echo_stdout_stderr=True, autoscroll=True, auto_refresh=True)]
# [sg.Output(size=(60,15), font='Courier 8', expand_x=True, expand_y=True)]
]
layout = [[sg.MenubarCustom(menu_def, key='-MENU-', font='Courier 15', tearoff=True)],
[sg.Text('Specify the information below and press start', size=(38, 1), justification='center', font=("Helvetica", 16), relief=sg.RELIEF_RIDGE, k='-TEXT HEADING-', enable_events=True)]]
layout += [[sg.TabGroup([[sg.Tab('Input Elements', input_layout),
sg.Tab('Output', logging_layout)]], key='-TAB GROUP-', expand_x=True, expand_y=True),
]]
layout[-1].append(sg.Sizegrip())
window = sg.Window('Google maps webscraper', layout,
grab_anywhere=True, resizable=True, margins=(0, 0), use_custom_titlebar=True, finalize=True, keep_on_top=True)
window.set_min_size(window.size)
return window
def main():
window = make_window(sg.theme())
# This is an Event Loop
while True:
event, values = window.read(timeout=100)
# keep an animation running so show things are happening
if event not in (sg.TIMEOUT_EVENT, sg.WIN_CLOSED):
print('============ Event = ', event, ' ==============')
print('-------- Values Dictionary (key=value) --------')
for key in values:
print(key, ' = ', values[key])
if event in (None, 'Exit'):
print("[LOG] Clicked Exit!")
break
elif event == "Open File":
print("[LOG] Clicked Open File!")
folder_or_file = sg.popup_get_file(
'Choose your file', keep_on_top=True)
sg.popup("You chose: " + str(folder_or_file), keep_on_top=True)
print("[LOG] User chose file: " + str(folder_or_file))
elif event == "Start":
thread_selenium = threading.Thread(target=start_script, args=(values,))
thread_selenium.start()
elif event == "Skip":
print('Skip')
elif event == "Add":
print('test')
window.close()
exit(0)
if __name__ == '__main__':
sg.theme('system default for real')
sg.theme('DefaultNoMoreNagging')
main()

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

check if all inputs has values in pysimplegui

I have a window that has multiple inputs and combo selectbox like this
main_layout = [[sg.Text('First Name', size=(15, 1)),
sg.InputText(key='gname', size=(25, 1))],
[sg.Text('V Type', size=(15, 1)),
sg.Combo(['option 1','option 2','option 3'],key="vtype",size=(25, 1)],
[sg.Text('Last Name', size=(15, 1)),
sg.InputText(key='glastname', size=(25, 1)],
[sg.Submit('Submit'),sg.Cancel('Cancel')]]
layout = [[sg.Column(main_layout,scrollable=True,vertical_scroll_only=True, size=(755,500))]]
window = sg.Window('Form', layout, font='arial',resizable=True, element_justification='l',size=(755,500))
event, values = window.read()
if event == 'Cancel' or event == sg.WIN_CLOSED:
sys.exit()
name_check = window['gname'].get().strip()
if name_check == '':
sg.popup(f"Field is Required")
window.close()
I'm already using name_check = window['gname'].get().strip() for the name event that checks it isn't blank what I want to do is on clicking submit check all inputs to have a value and not to be blank because the code above is a form and the form is long I only wrote few of them for example
The form data will be written into a text file with a regular expression and if the value would be blank the app crashes, so I want something that I can check multiple event keys at once
How can I do that?
Using window.key_dict to get a dictionary with all key:element pairs for all elements, then iterate each item to confirm if it is sg.Input element, and all inputs are not null string.
import PySimpleGUI as sg
sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 12))
layout = [
[sg.Text(f"Line {i: >2d}:"), sg.Input("")] for i in range(10)] + [
[sg.Button("Submit")],
[sg.StatusBar("", size=(20, 1), key='Status')]
]
window = sg.Window('Title', layout, finalize=True)
prompt = window['Status'].update
input_key_list = [key for key, value in window.key_dict.items()
if isinstance(value, sg.Input)]
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == "Submit":
if all(map(str.strip, [values[key] for key in input_key_list])):
prompt("All inputs are OK !")
else:
prompt("Some inputs missed !")
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

Categories