I am having trouble save the user's name into a list once order is pressed. I also need to store the user's selction with the buttons into the same list--i believe i need a dis tionary for this but I am completely lost.
For example:
John presses Burger, Onions, Bacon, and Eggs. he hits submit.
I need the out put to relay "John's Order: Burger, Onions, Bacon, Eggs. Total: $XX.XX"
is this possible? And maybe if someone knows how to save the output into a onedrive file
here is my code:
import PySimpleGUI as sg
menu_dictionary = {
"Cheese":0.50,
"Sandwhich":1.75,
"Pickles":0.25,
"Hot Dog":1.25,
"Burger": 3.5,
"Onions": 0.75,
"Bacon": 1.25,
"Eggs": 1.00,
"Gatorade": 1.25
}
total=0
name= []
sg.theme('Dark Amber')
layout = [
[sg.Text("Welcome to the MAF Menu")],
[sg.Text("Enter your name:"), sg.Input(), sg.Button("Order")],
[sg.Text("Entrees"), sg.Button("Burger"), sg.Button("Sandwhich"), sg.Button("Hot Dog"), sg.Button("Eggs")],
[sg.Text("Sides"),sg.Button("Onions"), sg.Button("Pickles"), sg.Button("Cheese")],
[sg.Text("Total $" + str(total), key='Total'), sg.Text(name, key='Order')],
[sg.Button("Exit"), sg.Button("Clear")],]
window = sg.Window('MAF Menu', layout)
while True:
event, values = window.read()
if event == "Order":
name.append()
window['Order'].update("Order")
if event in menu_dictionary:
total = total + menu_dictionary[event]
window['Total'].update("Total $" + str(total))
if event == "Clear":
total=0
window['Total'].update("Total $0")
if event == sg.WIN_CLOSED or event == 'Exit':
sg.popup_no_titlebar('Are you sure?')
break
window.close()
I keep getting errors that the list is not populating
You just simply not need to append the name as your name is single value comming from textbox, and use a list to keep track of all items ordered
import PySimpleGUI as sg
menu_dictionary = {
"Cheese":0.50,
"Sandwhich":1.75,
"Pickles":0.25,
"Hot Dog":1.25,
"Burger": 3.5,
"Onions": 0.75,
"Bacon": 1.25,
"Eggs": 1.00,
"Gatorade": 1.25
}
total=0
items = []
name = ''
sg.theme('Dark Amber')
layout = [
[sg.Text("Welcome to the MAF Menu")],
[sg.Text("Enter your name:"), sg.Input(), sg.Button("Order")],
[sg.Text("Entrees"), sg.Button("Burger"), sg.Button("Sandwhich"), sg.Button("Hot Dog"), sg.Button("Eggs")],
[sg.Text("Sides"),sg.Button("Onions"), sg.Button("Pickles"), sg.Button("Cheese")],
[sg.Text("Total $" + str(total), key='Total'), sg.Text(name, key='Order')],
[sg.Button("Exit"), sg.Button("Clear")],]
window = sg.Window('MAF Menu', layout)
while True:
event, values = window.read()
if event == "Order":
print(values[0])
order = ", ".join(items)
order = "{}'s Order: {}".format(name, order)
print(order)
if event in menu_dictionary:
total = total + menu_dictionary[event]
if event not in items:
items.append(event)
window['Total'].update("Total $" + str(total))
if event == "Clear":
total=0
items = []
window['Total'].update("Total $0")
if event == sg.WIN_CLOSED or event == 'Exit':
sg.popup_no_titlebar('Are you sure?')
break
window.close()
Related
I want an event to run when I type in the input, that works.
But only when I type something, not when the field is empty, I want that too
Here's a little template code I wrote that resembles my issue
import PySimpleGUI as sg
list1 = ['a', 'b', 'c']
matches = []
out = []
layout = [
[sg.InputText('', key='-search-', change_submits=True)],
[sg.Listbox(values=out, key='-list-', size=(10,10))]
]
window = sg.Window('Search', layout, size=(300, 300))
while True:
event, values = window.read()
if values['-search-']:
SearchTerm = values['-search-']
SearchTerm.replace("['", "")
SearchTerm.replace("']", "")
print("Search Term = " + SearchTerm)
if SearchTerm == "":
out = list1
window.Element('-list-').Update(values=list1)
if SearchTerm != "":
for i in list1:
if SearchTerm in i:
if i not in matches:
matches.append(i)
outlist = matches
window.Element('-list-').Update(values=outlist)
if event == sg.WIN_CLOSED or event == 'Exit':
break
There's re lot of events in event loop, so you have to decide how to check what the event is. For example, if values['-search-']: will be failed it you close the window and values maybe None, then you will get exception TypeError: 'NoneType' object is not subscriptable.
In your event loop, you didn't check the case values['-search-']=='', but just check SearchTerm == "" under the event values['-search-']!=''.
The pattern for event loop maybe like this
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == '-search-':
if values[event]:
""" Code if Input element not empty """
else:
""" Code if Input element is empty """
window.close()
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 have a simple calculator with a fixed constant and another entry to be added to the constant. I am struggling to deal with these entries(VARIABLE) being negative ie -1234 since i cast an int() on the input so clearly this leads to problems when trying to calculate the sum.
import PySimpleGUI as sg
columns = ["FIXED","VARIABLE","RESULT"]
param = (20,3) # size of the main window
def CALCULATOR():
sg.theme('Dark Brown 1')
listing = [sg.Text(u, size = param) for u in columns]
core = [
sg.Input(f"{10}", size = param),
sg.Input(size = param,enable_events=True,key='NUMBER'),
sg.Input(size = param)]
mesh = [[x,y] for (x,y) in list(zip(listing, core))]
window = sg.Window('CALCULATOR', mesh, font='Courier 12').Finalize()
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == "SEND":
break
elif event == "NUMBER":
variable = int(values['NUMBER'])
fixed= int(values[0])
for element, value in zip(core[2:], [variable+fixed]):
element.update(value=value)
else:
print("OVER")
window.close()
CALCULATOR()
You can wrap your if-statements in a try-except statement, and then handle the updates for when there is a ValueError:
while True:
event, values = window.read()
try:
if event == sg.WINDOW_CLOSED:
break
elif event == "SEND":
break
elif event == "NUMBER":
variable = int(values['NUMBER'])
fixed = int(values[0])
core[2].update(variable+fixed)
else:
print("OVER")
except ValueError:
core[2].update("ValueError!")
The above code "catches" the ValueError that is triggered once you input something that doesn't translate well into an integer, after that you can then update the field to inform the user why the results didn't output.
import random
import string
import PySimpleGUI as sg
filename = r'C:\Users\teeki\Documents\Passwords\passwords.txt'
def new_password():
print("For which account you want your password: ")
account = input();
length = int(input('\nHow long do you want your password to be: '))
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
#All possible symbols to be used in password
all_symbols = lower + upper + num + symbols
#we generate <length> long password and print it out
temp = random.sample(all_symbols,length)
password = "".join(temp)
# We save password to the passwords.txt
text_file = open(r'C:\Users\teeki\Documents\Passwords\passwords.txt' , 'a')
n = text_file.write('\n' + account + ' password: ' + password)
text_file.close()
print("Your password is: ", password)
def popup_text(filename, text):
layout = [
[sg.Multiline(text, size=(80, 25)),],
]
win = sg.Window(filename, layout, modal=True, finalize=True)
while True:
event, values = win.read()
if event == sg.WINDOW_CLOSED:
break
win.close()
sg.theme('LightBlue3')
layout = [[sg.Text("Welcome to Password Generator")], [sg.Button("Exit")], [sg.Button("Password List"), sg.Button("New Password")]]
window = sg.Window("Password Generator", layout)
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
elif event == "Password List":
with open(filename, "rt", encoding='utf-8') as f:
text = f.read()
popup_text(filename, text)
elif event == "New Password":
new_password()
window.close()
I need help with making a popup. So far the code works just fine, but instead of when i press on New Password printing on terminal i want it to open new popup where i would have 2 input fields and button to save password into .txt file.
I've tried messing around with sg.Popup but i cant get it to work properly. So any advice would be appreciated.
Example for you,
import random
import string
import PySimpleGUI as sg
def generate_password(account, length):
return 'new password'
filename = r'C:\Users\teeki\Documents\Passwords\passwords.txt'
def new_password():
layout = [
[sg.Text("Password Account"), sg.Input(key='account')],
[sg.Text("Password Length "), sg.Input(key='length' )],
[sg.Button("Generate"), sg.Text("", size=(0, 1), key='password')],
]
window = sg.Window('New Password', layout, modal=True)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == "Generate":
account = values['account']
length = int(values['length'])
password = generate_password(account, length)
if password:
window['password'].update(value=password)
else:
window['password'].update(value='')
window.close()
def popup_text(filename, text):
sg.Window(filename, [[sg.Multiline(text, size=(80, 25))]], modal=True
).read(close=True)
sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 16))
layout = [
[sg.Text("Welcome to Password Generator")],
[sg.Button("Exit")],
[sg.Button("Password List"), sg.Button("New Password")]]
window = sg.Window("Password Generator", layout)
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
elif event == "Password List":
with open(filename, "rt", encoding='utf-8') as f:
text = f.read()
popup_text(filename, text)
elif event == "New Password":
new_password()
window.close()
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