boolean value only works once and then stops - godot

so im using godot and im trying to set up a button to switch between fullscreen and not, and when i run it and click the button it switches to fullscreen but then it decides to not want to switch back
code below:
extends Button
var on = false
func _on_FullScreen_pressed():
if on == true:
on = false
OS.window_fullscreen = false
$Label.text = "Fullscreen: No"
if on == false:
on = true
OS.window_fullscreen = true
$Label.text = "Fullscreen: Yes"
i assume the problem is happening because i set on to false in the top if statement, then in the bottom if statement reads it as false and sets it back
if that is the case please provide me with a way to fix

Change the second if to elif. Or to else and remove the condition

You could use a toggle like this:
extends Button
var fullscreen = false
func _on_FullScreen_pressed():
fullscreen = !fullscreen #toggles fullscreen
OS.window_fullscreen = fullscreen
if(fullscreen):
$Label.text = "Fullscreen: Yes"
else:
$Label.text = "Fullscreen: No"
or even better, use a toggleable button with the correct event:
extends Button
func _ready():
set_toggle_mode(1)
func _on_Button_toggled(button_pressed):
OS.window_fullscreen = button_pressed
if button_pressed:
$Label.text = "Fullscreen: Yes"
else:
$Label.text = "Fullscreen: Yes"

extends Button
var on = false
func _on_FullScreen_pressed():
if on == true:
on = false
OS.window_fullscreen = false
$Label.text = "Fullscreen: No"
else:
on = true
OS.window_fullscreen = true
$Label.text = "Fullscreen: Yes"

Related

How do I open several windows in PySimpleGui, each window uses the same function and each window executes this function with a time interval

How do I open several windows in PySimpleGui, each window uses the same function and each window executes this function with a time interval.
The window has the same layout, it's just an output or multiline to show what the function is doing.
The function has a loop that lasts around 24 hours running, but it can run from 0 to 'x' hours.
I use Python and PySimpleGui
Not sure if it work all the time, didn't do more test, just for demo, popup windows not well placed when open.
Note: It won't return WINDOW_CLOSE_ATTEMPTED_EVENT from read_all_windows when click close button of window if option enable_close_attempted_event of Window set to True. It maybe a bug for this moment.
from time import sleep
import threading
import PySimpleGUI as sg
def function(win, username):
global login
while login[username][3]:
sleep(1)
win.write_event_value('ACK', username)
win.write_event_value('Done', username)
def popup(username):
sg.theme('DarkBlue4')
layout = [[sg.ProgressBar(100, orientation='H', size=(20, 20), key='Progress')]]
win = sg.Window(username, layout, finalize=True, enable_close_attempted_event=True)
return win
users = {
'Jason' : '778877',
'Michael': '123456',
'William': 'aabbcc',
}
sg.theme('DarkBlue3')
layout = [
[sg.Text('Username'), sg.Push(), sg.Input(do_not_clear=False, key='Username')],
[sg.Text('Password'), sg.Push(), sg.Input(do_not_clear=False, key='Password')],
[sg.StatusBar('', size=10, expand_x=True, key='Status')],
[sg.Push(), sg.Button('Execute'), sg.Push()],
]
window = sg.Window('System', layout, finalize=True, enable_close_attempted_event=True)
status = window['Status']
login, windows, bye = {}, {}, False
while True:
win, event, values = sg.read_all_windows()
print(repr(event))
if event == sg.WIN_CLOSED: # sg.WINDOW_CLOSE_ATTEMPTED_EVENT:
sg.theme('DarkBlue5')
if sg.popup_yes_no("Are you sure to close ?") == 'Yes':
if win in windows:
username = windows[win]
login[username][3] = False
else:
if login:
bye = True
for username in login:
login[username][3] = False
else:
break
elif event == 'Execute':
username, password = values['Username'], values['Password']
if username not in users:
status.update('Wrong username !')
elif password != users[username]:
status.update('Wrong password !')
elif username in login:
status.update('User executing !')
else:
w = popup(username)
thread = threading.Thread(target=function, args=(w, username), daemon=True)
login[username] = [w, thread, 0, True]
windows[w] = username
thread.start()
elif event == 'ACK':
username = values[event]
login[username][2] = count = (login[username][2] + 10) % 101
win['Progress'].update(count)
elif event == 'Done':
username = values[event]
win.close()
del login[username]
del windows[win]
if not login and bye:
break
for win in windows:
win.close()
window.close()

Ask dialog saves in the wrong map

When asked to choose a savefile location, I'll choose a map called "timelapse".
but the pictures are saved in the map before the timelapse. as in;
/home/pi instead of /home/pi/timelapse
It appears I accidentally put a default save location in the code? because it won't change the location, but I never coded it should specifically safe in /home/pi
I've tried adding manually a "/" to the text in the hope it would open the timelapse map, but I get an error with permission denied.
Creating a different submap didn't work, it still saves in /home/pi
class Capture:
def __init__(self, waittime=30):
self.capture_stop = False
self.capture_waittime = waittime
self.thread = None
self.capture_running = False
self.folder = ''
def capture_worker(self):
self.capture_running = True
try:
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
for filename in camera.capture_continuous(self.folder+'-{timestamp:%H-%M-%S-%f}.jpg'):
i = 0
while i < self.capture_waittime:
time.sleep(0.1)
i += 0.1
if self.capture_stop:
return
finally:
self.capture_running = False
self.capture_stop = False
def start(self):
if not self.capture_running:
self.thread = threading.Thread(target=self.capture_worker)
self.capture_stop = False
self.thread.start()
def stop(self):
if self.capture_running:
self.capture_stop = True
def isRunning(self):
return self.capture_running
def setWaitTime(self, waittime):
self.capture_waittime = waittime
def setFolder(self, folder):
capture.setFolder(folder)
self.folder = folder
capture = Capture()
def startButton():
interval = float(var_2.get())
capture.setWaitTime(interval)
capture.start()
def stopButton():
capture.stop()
def chooseDir():
root.folder = filedialog.askdirectory(
parent=root, initialdir="/home/pi/", title='Please choose a save location')
I expect the pictures to be saved in the map I specifically chose. I also hope to receive some criticism on my ask dialog code so that I can improve it.

Bringing dialog window in from of Python window

My application has two separate dialog windows prior to opening the main application window. I am unable to figure out how to get the second dialog window (the calendar) to open in from of the black python screen (I apologize for my ignorance I don't know the name).
The messagebox contained in "rundate" opens first. If "no" is selected then the app_window opens. It is the app_window that gets hidden
conn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq='+db)
cur = conn.cursor()
app_window = tk.Tk()
app_window.geometry("1x1+0+0")
app_window.overrideredirect(True)
app_window.transient()
def rundate():
result = tkinter.messagebox.askyesno(title="Rundate", message="back 7 days?")
if result == True:
end = date.today()
start = date.today() - timedelta(7)
daterange = [pd.date_range(start, end)]
for single_date in daterange:
x = single_date.strftime("%m/%d/%Y")
rundate = x
print(rundate)
return rundate
else:
app_window.wm_title("Pick1")
app_window.geometry("250x150+100+100")
app_window.overrideredirect(False)
#app_window.mainloop()
cm = pick1.CalendarFrame(app_window)
cm.grid()
app_window.wait_variable(cm.wait_for_result)
return cm.rundate
rundate = rundate()
print(rundate)
Then a whole bunch of code for queries and whatnot then
After the messagebox is returned "yes" OR the dates are selected from the calendar then the interface gets initiated
# Initiate interface
root = Tk()
master = Frame(root, name='master')
master.pack(fill=BOTH)
root.geometry("800x800+300+100")
root.title('WeeklyReport')
menu_bar = Menu(root)
def exit():
root.destroy()
root.wait_window
I finally figured it out by adding "lift" Thank you!
app_window = tk.Tk()
app_window.geometry("1x1+0+0")
app_window.overrideredirect(True)
app_window.transient()
app_window.lift()

Why does my script continue to 'while' loop when if statement is true?

At line 11, where the user chooses the cancel button on the easyGui. enterbox:
Code
from easygui import*
def children_menu():
title2 = "Children."
children_menu = ["1: Register a child.", "2: List of registered children."]
button = buttonbox("Choose an option", title2, choices=children_menu)
if button == children_menu[0]:
enter1 = enterbox(msg="Enter the child's first name.", title=' ', default='', strip=True, image=None, root=None)
if enter1 is None:
main()
return
else:
while enter1 == "" or enter1.isalpha() == False:
enter1 = enterbox(msg="Invalid entry. Please enter the child's first name using letters only.",title=' ', default='', strip=True, image=None, root=None)
enter2 = enterbox(msg="Enter the child's last name.", title=' ', default='', strip=True, image=None, root=None) # ask user to enter child's first name
while enter2 == "" or enter2.isalpha() == False:
if enter2 is None:
main()
else:
enter2 = enterbox(msg="Invalid entry. Please enter the child's last name using letters only.", title=' ', default='', strip=True, image=None,root=None)
child_name = (enter1 + " " + enter2).title()
file = open("Children.txt", 'a')
file.write(child_name + "\n")
file.close()
if button == children_menu[1]:
file = open("Children.txt", 'r')
lineList = file.readlines()
lineList.sort()
print("List of children's names in alphabetical order:")
for line in lineList:
print(line, end="")
file.close()
main()
def main():
title1 = "Main menu."
main_menu = ["1: Children", "2: Groups", "3: Educators", "4: Tags", "5: Cancel"]
button = buttonbox("Choose an option", title1, choices=main_menu)
if button == main_menu[0]:
children_menu()
elif button == main_menu[1]:
group_menu()
elif button == main_menu[2]:
button = "3"
title4 = "Educators."
educator_menu = ["1: Register an educator.", "2: List of registered educators."]
button = buttonbox("Choose an option", title4, choices=educator_menu)
elif button == main_menu[3]:
button = "4"
title4 = "Tags."
tags_menu = ["1: Create tags", "2: List of tags."]
button = buttonbox("Choose an option", title4, choices=tags_menu)
else:
button = "You cancelled."
main()
Questions
Why does the code continue to the while-loop even though the user's choice returns a NoneType ?
Doesn't it meet the condition of the if-statement?
Shouldn't the script return to the main() function that is being called?

Putting a time restriction on input

I have searched this for a while but I have not found a way that has worked
what I want to do is this:
prompt=str(input('press "l" within two seconds:'):
if prompt=='l':
print('ta da')
else:
print('loser')
how do I add a time restriction to that?
If you are not caring about beeing thread safe, this is a good aproach:
import datetime
import threading
win = False
time_out = False
def MyThread1(t_name, prompt, time_var):
global win
global time_out
prompt=str(input('press "l" within two seconds:'))
win = False
if(not time_out and prompt == 'l'):
win = True
print('ta da')
else:
print('loser')
def MyThread2(t_name, prompt, time_var):
global win
global time_out
while (time_var > datetime.datetime.now()):
pass
time_out = True
time_var = datetime.datetime.now() + datetime.timedelta(seconds=2)
prompt = 'l'
t1 = threading.Thread(target=MyThread1, args=("Thread-1", prompt, time_var))
t2 = threading.Thread(target=MyThread2, args=("Thread-2", prompt, time_var))
t1.start()
t2.start()

Resources