Error while restarting the Tkinter program dynamically by destroying root and recreating again by calling functions - python-3.x

import configparser
from tkinter import *
from tkinter import filedialog,messagebox
from tkinter.filedialog import asksaveasfile
from customtkinter import *
import os
import time
import wikipedia
config=configparser.ConfigParser()
config.read("config.ini")
def change_config():
messagebox.showinfo("Information","App is going to restart in few seconds")
print(mode.get())
print(color.get())
global location
config.set("THEME","mode",str(mode.get()))
config.set("VOICE","voice",str(gender.get()))
if color.get() =="pink":
location="C:/Users/DELL/Documents/python programs/notepad/custom_theme.json"
config.set("THEME","color",location)
else :
config.set("THEME","color",color.get())
with open("config.ini","w") as configfile:
config.write(configfile)
restart()
def main():
global root,label,frame1,config_color,config_mode,config_gender
root=CTk()
root.geometry("700x600")
root.resizable(0,0)
root.title("Notepad")
frame1=CTkFrame(root,width=150,height=580)
frame1.pack_propagate(False)
frame1.place(x=10,y=10)
config_color=config.get("THEME","color")
config_mode=config.get("THEME","mode")
config_gender=config.get("VOICE","voice")
set_appearance_mode(config_mode)
set_default_color_theme(config_color)
label=CTkLabel(root,text="File",width=520,height=40,font=("Algerian",30))
label.place(x=170,y=10)
global S
global text_area
text_area=CTkTextbox(root,height=580,width=520,)
text_area.place(x=170,y=60)
global button,commands,button_text
button_text="Settings"
commands=settings
button=CTkButton(frame1,text=button_text,command=settings)
button.pack(padx=10,pady=10)
root.mainloop()
def settings():
global submit,mode,color,config_color,config_mode,gender
window=CTkToplevel(root)
window.title("Settings")
window.geometry("200x300")
label1=CTkLabel(window,text="Mode").pack(pady=5)
mode=CTkOptionMenu(window,values=["light","dark"])
mode.pack(pady=5,padx=5,anchor=CENTER)
label2=CTkLabel(window,text="Color").pack(pady=5)
color=CTkOptionMenu(window,values=["pink","blue","green","dark-blue"])
color.pack(pady=5)
label3=CTkLabel(window,text="speech-gender").pack(pady=5)
gender=CTkOptionMenu(window,values=["male","female"])
gender.pack(pady=5)
submit=CTkButton(window,text="Submit",command=change_config)
submit.pack(pady=20)
window.mainloop()
if __name__=="__main__":
def restart():
time.sleep(5)
root.destroy()
main()
main()
I want to create a notepad , where we can change themes and colors.
I have made config.ini file where i save the current mode, color and the voice type for the notepad ( voicetype is for text-to-speech functionality that i have added here ) becuase while using customtkinter we can set default color theme and cannot change it once initialized in a program.
The program now save the selected preferences in config.ini file and grab it when run again.
I want the program to run again itself without having the need to explicitly run it again.
Though program is running i am still getting this error at backend:
invalid command name "2912423726080check_dpi_scaling"
while executing
"2912423726080check_dpi_scaling"
("after" script)
invalid command name "2912423728512update"
while executing
"2912423728512update"
("after" script)
invalid command name "2912423728448<lambda>"
while executing
"2912423728448<lambda>"
("after" script)
I want to know what this error means so that the users might not face problem in future while using this app.
Thanks in advance for helping.

Related

JupyterLab 3: how to get the list of running servers

Since JupyterLab 3.x jupyter-server is used instead of the classic notebook server, and the following code does not list servers served with jupyter_server:
from notebook import notebookapp
notebookapp.list_running_servers()
None
What still works for the file/notebook name is:
from time import sleep
from IPython.display import display, Javascript
import subprocess
import os
import uuid
def get_notebook_path_and_save():
magic = str(uuid.uuid1()).replace('-', '')
print(magic)
# saves it (ctrl+S)
# display(Javascript('IPython.notebook.save_checkpoint();')) # Javascript Error: IPython is not defined
nb_name = None
while nb_name is None:
try:
sleep(0.1)
nb_name = subprocess.check_output(f'grep -l {magic} *.ipynb', shell=True).decode().strip()
except:
pass
return os.path.join(os.getcwd(), nb_name)
But it's not pythonic nor fast
How to get the current running server instances - and so e.g. the current notebook file?
Migration to jupyter_server should be as easy as changing notebook to jupyter_server, notebookapp to serverapp and changing the appropriate configuration files - the server-related codebase is largely unchanged. In the case of listing servers simply use:
from jupyter_server import serverapp
serverapp.list_running_servers()

Running Django with Pyto on iPad

I am trying to build my first Webb app using Django. I’m using my iPad because I am on the move a lot. Anyways, I’m trying to follow Django’s instructions for building a poll application. I got the server running but when i made the changes that should have printed the Hello World but its now its giving me a ModuleNotFoundError.
I’ve tried copy and pasting the lines of code from Django’s website and I’ve tried to type it in on my own.
ModuleNotFoundError: No module named 'WellnessApp'
import os
`import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WellnessProject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
#if __name__ == '__main__':
# main()
if __name__ == '__main__':
import background as bg
with bg.BackgroundTask() as b:
main()`

Agora - unable to merge video .ts files into one single video file

I am using agora.io for video calling. I am running script on my localhost.
I am able to record the video successfully but they are multiple .ts files.
I downloaded python script from agora website and ran it. It runs successfully without any error But it does not generate any single video file, in short script run successfully but nothing happens.
No errors, no new file generated.
The code I am using is:
#!/usr/bin/env python
import time
import re
import os
import sys
import signal
import glob
import parser_metadata_files
import video_convert
from optparse import OptionParser
import traceback
if '__main__' == __name__:
import sys
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGQUIT, signal.SIG_IGN)
parser = OptionParser()
parser.add_option("-f", "--folder", type="string", dest="folder", help="Convert folder", default="")
parser.add_option("-m", "--mode", type="int", dest="mode", help="Convert merge mode, \
[0: txt merge A/V(Default); 1: uid merge A/V; 2: uid merge audio; 3: uid merge video]", default=0)
parser.add_option("-p", "--fps", type="int", dest="fps", help="Convert fps, default 15", default=15)
parser.add_option("-s", "--saving", action="store_true", dest="saving", help="Convert Do not time sync",
default=False)
parser.add_option("-r", "--resolution", type="int", dest="resolution", nargs=2,
help="Specific resolution to convert '-r width height' \nEg:'-r 640 360'", default=(0, 0))
(options, args) = parser.parse_args()
if not options.folder:
parser.print_help()
parser.error("Not set folder")
try:
print('1')
os.environ['FPSARG'] = "%s" % options.fps
print('2')
parser_metadata_files.cmds_parse(["dispose", options.folder])
print('3')
video_convert.do_work()
print('4')
parser_metadata_files.cmds_parse(["clean", options.folder])
print('5')
except Exception as e:
traceback.print_exc()
The command I am running is:
/usr/local/bin/python3.7 convert.py -f /Users/msmexmac/Desktop/Cloud_Recording_tools/tiles/ -m 3 -p 30
I downloaded the script from this page.
The reason you see multiple .ts files is because, after the recording starts, the Agora server automatically splits the recorded content into multiple TS/WebM files and keeps uploading them to the third-party cloud storage until the recording stops.
Make sure to follow the steps in the below-given link for uploading the recorded video:
https://docs.agora.io/en/cloud-recording/cloud_recording_rest
It is crucial to get the "uploaded" callback to proceed further.

Kivy window dont't show up - AttributeError: module 'collections' has no attribute 'namedtuple'

Why I'm getting this error --> AttributeError: module 'collections' has no attribute 'namedtuple'. Whats wrong with my code..
I'm using python 3.5.2 on windows. When I execute my code on IDLE it can run - show up the kivy window, but when I execute C:\POS\operator\python operator.py it failed.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class OperatorWindow(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class OperatorApp(App):
def build(self):
return OperatorWindow()
if __name__ == "__main__":
OperatorApp().run()
It looks like your file name is at fault here since there's also a standard library module called operator. I've got the same error but when I renamed your sample code from operator.py to test.py, it worked normally.

How not to call initialize at each request with Tornado

I want to set variables when starting my Tornado webserver, so I tried to override initialize on my RequestHandler class. But apparently, initialize is launched each time a request is made, according to the following code and its output:
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def initialize(self):
print("Launching initialization...")
def get(self):
print("Get: {}{}".format(self.request.host, self.request.uri))
app = tornado.web.Application([=
(r"/.*", MainHandler)
])
def runserver():
import tornado.ioloop
app.listen(8080)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
runserver()
stdout:
~ ➤ ./redirector.py
Launching initialization...
Get: 127.0.0.1:8080/
Launching initialization...
Get: 127.0.0.1:8080/favicon.ico
Launching initialization...
Get: 127.0.0.1:8080/favicon.ico
Launching initialization...
Get: 127.0.0.1:8080/
This behavior is the complete contrary to what is written in the doc:
Hook for subclass initialization.
(Meaning it is called at the end of __init__)
So, does anybody know how to do what I want to ?
Thanks in advance.
It's not contrary to the doc; have a look at the Structure of a Tornado app section. A RequestHandler object is created for each request.
If you want code to be executed when the app is started only, subclass the Application class and override __init__, or just put it in your runserver function.

Resources