Updating Values in PySimpleGUI - python

I have a bot that fetches data from a website through selenium and I want to plot that data on a GUI. Bot sends Email and Notifications as well, I need someway to change value of real_email and real_noti Live, anytime.
Whole BOT Code is in a while True: loop.
Issue that I am having right now is, I was thinking of adding my BOT CODE and pysimplegui in the same while loop but the program stops at event, values = window.read() for input and will not go further input is passed.
Here is the Demo Code.
import PySimpleGUI as sg
sg.theme('DarkAmber') # Keep things interesting for your users
elem = sg.Text('Email and Notfication ON', key='-TEXT-')
layout = [[elem],
[sg.Input(key='-IN-')],
[sg.Input(key='-IN')],
[sg.Button('Ok'), sg.Exit()]]
window = sg.Window('Window that stays open', layout)
real_email = "On"
real_noti = "On"
while True: # The Event Loop
event, values = window.read()
email = values['-IN-']
notification = values['-IN']
if email == "On":
real_email = "On"
elif email == "Off":
real_email = "Off"
if notification == "On":
real_noti = "On"
elif notification =="Off":
real_noti = "Off"
if event in (None, 'Exit'):
break
print("Testing Print Value After .read()")
window.close()
I just want to change these 2 values in this loop. Maybe a way to use Checkbox or Only Buttons?

You have to set enable_event=True in the sg.Input(key='-IN-') will be sg.Input(key='-IN-', enable_event=True)

Related

How to record mouse and keyboard movement simultaneously, and store it as a variable that could be placed in a function or loop with Python?

So I want to start a project that records my keyboard input and mouse movement for a sandbox PC games. I love farming, however whether I'm tired, and taking a short break to make a coffee or have a phone call. When I come back my farm gets annihilated.
I tried and made this one, but it seems not to work. Any way to make it better with the possibility to implement the recorded inputs in a loop function?
import pyautogui
def record_movement():
# Initialize variables to store mouse and keyboard events
mouse_events = []
keyboard_events = []
# Start recording mouse and keyboard events
pyautogui.PAUSE = 0.001 # Set a small pause to record events more accurately
pyautogui.FAILSAFE = False # Disable failsafe feature to allow for recording
recording = True
while recording:
event = pyautogui.getEvent()
if event.event_type == 'MouseMove':
mouse_events.append(event)
elif event.event_type == 'KeyDown':
keyboard_events.append(event)
elif event.event_type == 'KeyUp':
keyboard_events.append(event)
elif event.event_type == 'Quit':
recording = False
return mouse_events, keyboard_events
def replay_movement(mouse_events, keyboard_events):
# Replay recorded mouse and keyboard events
for event in mouse_events:
pyautogui.moveTo(event.x, event.y)
for event in keyboard_events:
if event.event_type == 'KeyDown':
pyautogui.press(event.name)
elif event.event_type == 'KeyUp':
pyautogui.keyUp(event.name)
# Test:
mouse_events, keyboard_events = record_movement()
replay_movement(mouse_events, keyboard_events)

Reacting to a users choice in a combo-box (Event)

I have a working form in PySimpleGUI with a combo-box.
I would like to update combo-box "y" (set the default of this combo-box) when the user selects a value in combo-box "x".
I think that I should capture the event and update the "y" element's value, in order to set the "default", but I haven't been able to figure out how to capture this event. I haven't found any good examples of this use case either.
Specifically, after the user chooses a 'Name' from the first combo-box, I would like to update the default value in the 'Status' combo-box:
import gspread
import pandas as pd
import PySimpleGUI as sg
.
.
.
lst = records_df.Label.to_list()
Status = ['A','B','C','D']
layout = [
[sg.Text('Please Choose:',size=(39,1))],
[sg.Combo(lst, key='combo', size=(20,1)),sg.Text('Name:', size=(18,1))],
[sg.Combo(Status, key='comboStatus', size=(20,1)),sg.Text('Status:', size=(18,1))],
[ sg.Button('Exit', key='Exit', size=(18,1)), sg.Button('Submit', key='Submit', size=(20,1))]
]
.
.
.
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
elif event == 'Submit':
window.close()
It's easier than you'd think. Just add enable_events=True to the combo-box, and it will pass an event every time an item is chosen.
layout = [
[sg.Text('Please Choose:',size=(39, 1))],
[sg.Combo(lst, key='combo', size=(20, 1), enable_events=True), sg.Text('Name:', size=(18, 1))],
[sg.Combo(Status, key='comboStatus', size=(20, 1)),sg.Text('Status:', size=(18, 1))],
[sg.Button('Exit', key='Exit', size=(18, 1)), sg.Button('Submit', key='Submit', size=(20, 1))]
]
while True:
event, values = window.read()
if event == 'combo': # the event's name is the element's key
print(values)
I couldn't, however, get it to pass an event when you manually enter text into the combobox, even after pressing enter. Hopefully that isn't an issue for your use-case.

My program freezes the moment my spammer made with pysimplegui, pyautogui and timer starts

when i press "submit" the program freezes can you guys please help me. I am new to pysimplegui and am trying to turn one of my practice programs into a gui.
Also could someone tell me how to make the arrows of the "spin" element functional?
If i made some stupid mistakes please do let me know, like i said I am new to this stuff so any help is really appreciated
import time
import PySimpleGUI as sg
import pyautogui as pyautogui
# img_viewer.py
layout=[
[
sg.Text("What do you want to do?"),
sg.Button("Spammer"),sg.Button("Encrypter"),sg.Button("Decrypter"),sg.Button("Password generator"),
sg.Button("Exit")
]
]
window = sg.Window("Multifunctiontool", layout)
layoutspammer=[
[
[sg.Text("Press Start to start the bot.")],
[sg.Text("Press Stop and then enter to stop the bot.")],
[sg.Button("Start"),sg.Button("Stop")]
]
]
layoutspammerwindow=[
[
[sg.Text("How many messages do you want to send?"),sg.Spin(0,key="spammer")],
[sg.Text("How long ist the cooldown? if not there just leave on 0"),sg.Spin(0,key="cooldown")],
[sg.Text("What is your message?"),sg.Input(key="message")],
[sg.Text("Do you want to leave a final message(Write down your message, if no just leave blank)?"),sg.Input(key="final_message")],
[sg.Button("submit"),sg.Button("Exit")]
]
]
layoutspammerwindow2=[
[
[sg.Text("please enter a valid parameter")],
[sg.Button("Continue"), sg.Button("Exit")]
]
]
spammerwindow= sg.Window("spammer",layoutspammer)
spammerwindow2= sg.Window("spammer",layoutspammerwindow,force_toplevel= True)
spammerwindow3= sg.Window("spammer",layoutspammerwindow2)
while True:
event,values=window.read()
if event== "Exit" or event== sg.WIN_CLOSED:
break
if event== "Spammer":
spammer_active = True
while spammer_active is True:
event, values = spammerwindow.read()
if event == "Start":
event, values = spammerwindow2.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
if event == "submit":
spammer = int(values['spammer'])
cooldown = int(values['cooldown'])
message = (values['message'])
final_message = (values['final_message'])
time.sleep(5)
for xi in range(int(spammer)):
pyautogui.typewrite(message)
time.sleep(int(cooldown))
pyautogui.press('enter')
print(xi)
pyautogui.typewrite(final_message)
pyautogui.press('enter')
break
elif event == "Stop" or event == sg.WIN_CLOSED:
spammer_active = False
else:
event, values = spammerwindow3.read()
if event == "Exit" or sg.WIN_CLOSED:
break
elif event == "Continue":
spammer_active = True
while spammer_active is True:
event, values = spammerwindow.read()
if event == "Start":
event, values = spammerwindow2.read()
if event == "submit":
spammer = int(values['spammer'])
cooldown = int(values['cooldown'])
message = (values['message'])
final_message = (values['final_message'])
time.sleep(5)
for xi in range(int(spammer)):
pyautogui.typewrite(message)
time.sleep(int(cooldown))
pyautogui.press('enter')
print(xi)
pyautogui.typewrite(final_message)
pyautogui.press('enter')
break
window.close()

I can't get button name to appear on gui or input to be saved when clicking on button using PySimpleGui

I am using PySimpleGUI and I want to be able to click on a Button and have that show up on the text under the button as the selection. The options are to split or data populate but I am unable to figure out how to make the event handler update the text or to save that option and then have the code act accordingly based on that option.
The code so far looks a little like this
import PySimpleGUI as sg
layout = [
[sg.Text('Would you like to SPLIT or SPLIT AND DATA POPULATE')],
[sg.Button('Split', key='-SPLIT-'), sg.Button('Split and Populate', key ='-SANDP-')],
[sg.Text('Current Process:'), sg.Text('Process', key='-PROCESS-')]
]
window = sg.Window('Title', layout,size=(1000,500))
while True:
event, values = window.read()
if event is None or event == 'EXIT':
break
if event == '-SPLIT-':
window['-PROCESS-'].update(values("-SPLIT-"))
choice1 = window['-PROCESS-'].update("split")
if event == '-Split and Populate-':
window['-PROCESS-'].update("Split and Populate")
choice2 = window['-PROCESS-'].update("Split and Populate")
window.close()
#psuedo code following
if choice1
bla bla bla
if choice2
bla bla bla
I want to be able to click and have that button name be stored in choice1 or choice 2 and also have that button name appear in the gui, is this posible?
The key will be the button_text of sg.Button if option key or k not specified and not duplicate, so there's no event for '-Split and Populate-'.
Most of time, the value of a sg.Button won't changed, so it won't be data in values from sg.Window().read. To get text on sg.Button, you can call method get_text of sg.Button.
For event generated from the key of element when you click on sg.Button or other element, then decide what to do in if ... elif ... else ... statement.
import PySimpleGUI as sg
layout = [
[sg.Text('Would you like to SPLIT or SPLIT AND DATA POPULATE')],
[sg.Button('Split', key='-SPLIT-'),
sg.Button('Split and Populate', key ='-SANDP-')],
[sg.Text('Current Process:'),
sg.Text('Process', size=(0, 1), key='-PROCESS-')]
]
window = sg.Window('Title', layout, size=(1000,500))
while True:
event, values = window.read()
if event is None or event == 'EXIT':
break
elif event in ('-SPLIT-', '-SANDP-'):
window['-PROCESS-'].update(value=window[event].get_text())
if event == '-SPLIT-':
pass
elif event == '-SANDP-':
pass
window.close()

how to make a savable ui in python

I have a project that allows the user to make a quiz on their own using some buttons and input
well i even want the user to be able to save their quiz in a file so they can load it in
i don't want something BIG!! a txt file will do..
i am using PySimpleGui and not Tkinter or anything..
i really don't know what i have made till now yet?(sorry i am not great with GUI)
i have a :
Main window
Editor window
And a form window
main window links the editor
editor links the form window
thanks for help in advance
if you need my code too then here
import pysimplegui as sg
layout = [
[sg.Button("Make new Form")],
[sg.Button("Open Form")]
]
window = sg.Window("Python Forms", layout)
def Form_Make():
layout_for_make_form = [
[sg.Button("Add multiple choice question")],
[sg.Button("Save Form")]
# some more items here..
]
make_form_window = sg.Window("Make a Form..", layout_for_make_form)
while True:
events, values = make_form_window.read()
if events == "Add multiple choice question":
pass # this should add a new multi choice question(working on it!)
elif events == "Save Form":
# save a form.. i am stuck on this.. :|
while True:
event,values = windows.read()
if event == "Make new Form":
Form_M()
i really don't know what it is doing yet i will have to make a new file and start from scratch :|
this will work for you :
import PySimpleGUI as sg
import os.path
layout = [
[sg.Button("Make new Form")],
[sg.Button("Open Form")],
[sg.Button("Exit")],
]
windows = sg.Window("Python Forms", layout)
questions = []
def Form_Make():
layout_for_make_form = [
[sg.Button("Add multiple choice question", key='add')],
[sg.Text('file path',size=(10,1)),sg.FileBrowse(key='filepath')],
[sg.Button("Save Form",key='save',visible=False)]
# some more items here..
]
make_form_window = sg.Window("Make a Form..", layout_for_make_form)
while True:
count = False
events, values = make_form_window.read()
if events == "add":
layout_for_question = [
[sg.Text('Must Enter all the filed for save question in file.')],
[sg.Text('Enter Question : ',size=(10,1)),sg.Input(key='question')],
[sg.Text('option1',size=(10,1)),sg.Input(key='option1')],
[sg.Text('option2',size=(10,1)),sg.Input(key='option2')],
[sg.Text('option3',size=(10,1)),sg.Input(key='option3')],
[sg.Text('option4',size=(10,1)),sg.Input(key='option4')],
[sg.Button('add')]
]
make_question_window = sg.Window('question ', layout_for_question)
while True:
events, values = make_question_window.read()
if events == None:
break
elif events == 'add' :
if values['question'] != '' and values['option1'] != '' and values['option2'] != '' and values['option3'] != '' and values['option4'] != '':
questions.append([values['question'],values['option1'],values['option2'],values['option3'],values['option4']])
print('value addded ')
count = True
if count == True:
make_form_window['save'].update(visible=True)
elif events == "save":
print(values['filepath'])
file = values['filepath']
if file != None:
f=open(file,'w+')
for x in questions:
for y in x:
f.write(y + '\n')
f.close()
print('save a form.. i am stuck on this.. :')
elif events == None:
break
while True:
event,values = windows.read()
if event == "Make new Form":
Form_Make()
elif event == 'Exit' or event == None :
break

Categories

Resources