how to make that every 10 sec automatically change the program background - python-3.x

how to make that every 10 sec automatically change the program background
and the colors will be randomly selected
color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
update:
i want use in this code:
app = wx.App()
window = wx.Frame(None, title = "test con", size=(800,300) )
window.SetMaxSize(wx.Size(800,300))
window.SetMinSize(wx.Size(800,300))
window.SetIcon(wx.Icon("eq.ico"))
window.SetBackgroundColour(color)
panel = wx.Panel(window, wx.ID_ANY)
suka = bat()
def on_timer():
label1aa.SetLabel(str(ram_uz()))
label8.SetLabel(doi)
label16.SetLabel(str(random.randint(1,100)))
label1a.SetLabel(str(bat()))
wx.CallLater(1000, on_timer)
panel.SetBackgroundColour(color)
panel.SetCursor(wx.Cursor(wx.CURSOR_HAND))

try this i hope it will help you
import threading
def change_color():
while True:
time.sleep(10)
color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
threading.Thread(target=change_color).start()

You could use a timer:
import threading
timer = threading.Timer(interval, function)
//interval is the lapse of time you want between each execution of the function "function"
timer.start()

Related

How to bring python message box in front?

I am trying to get windows message box pop in front but every time the message box is called it just pops up in the background on another monitor.
import ctypes
from time import sleep
sleep(5) # for switching to another window
MB_SETFOREGROUND = 0x10000
ctypes.windll.user32.MessageBoxW(None, "This should be in top", "Very important messsage", MB_SETFOREGROUND)
Using MB_SYSTEMMODAL worked to bring the window to the front.
import ctypes
from time import sleep
sleep(5) # for switching to another window
MB_SYSTEMMODAL = 0x00001000
ctypes.windll.user32.MessageBoxW(None, "This should be in top", "Very important message", MB_SYSTEMMODAL)
I always recommend using .argtypes and .restype to ensure parameters are marshaled correctly between Python and C and it allows ctypes to better error check parameters:
import ctypes as ct
import ctypes.wintypes as w
import time
dll = ct.WinDLL('user32', use_last_error=True)
dll.MessageBoxW.argtypes = w.HWND, w.LPCWSTR, w.LPCWSTR, w.UINT
dll.MessageBoxW.restype = ct.c_int
MB_SYSTEMMODAL = 0x00001000
IDOK = 1
print('Waiting...')
time.sleep(5)
result = dll.MessageBoxW(None, "This should be in top", "Very important message", MB_SYSTEMMODAL)
print(result == IDOK)

How to use Progress bar in pytube?

I want to implement a progress bar in my code, but neither the old nor the new way of implementation is working.
How to add progress bar?
this fix dosen't work in the latest version.
Here is the latest documentation
https://pypi.org/project/pytube/
from pytube import YouTube
url="https://youtu.be/J5EXnh53A1k"
path=r'D://'
yt = YouTube(url)
yt.register_on_progress_callback(show_progress_bar)#by commenting this line code works fine but no progress bar is displyed
yt.streams.filter(file_extension='mp4').first().download(path)
def show_progress_bar(stream, _chunk, _file_handle, bytes_remaining):
current = ((stream.filesize - bytes_remaining)/stream.filesize)
percent = ('{0:.1f}').format(current*100)
progress = int(50*current)
status = '█' * progress + '-' * (50 - progress)
sys.stdout.write(' ↳ |{bar}| {percent}%\r'.format(bar=status, percent=percent))
sys.stdout.flush()
You first need to define the progress bar function, say progress_function:
def progress_function(chunk, file_handle, bytes_remaining):
global filesize
current = ((filesize - bytes_remaining)/filesize)
percent = ('{0:.1f}').format(current*100)
progress = int(50*current)
status = '█' * progress + '-' * (50 - progress)
sys.stdout.write(' ↳ |{bar}| {percent}%\r'.format(bar=status, percent=percent))
sys.stdout.flush()
Then register the above defined function progress_function with the on_progress_callback as follows:
yt_obj = YouTube(<<youtube_video_url>>, on_progress_callback = progress_function)
Rest of the code follows:
yt_obj.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution().download(output_path='/home/myusername/Videos', filename='MyVideo')
Output looks like this:
↳ |██████████████████████████████████----------------| 68.4%
Have fun!!
I'm using progressbar2
def progress_Check(stream = None, chunk = None, file_handle = None, remaining = None):
percent = file_size - remaining + 1000000
try:
# updates the progress bar
bar.update(round(percent/1000000,2))
except:
# progress bar dont reach 100% so a little trick to make it 100
bar.update(round(file_size/1000000,2))
yt = YouTube(url, on_progress_callback=progress_Check)
yt = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()
Here is function used to download youtube video and display progress bar from shell:
from pytube import YouTube
from pytube.cli import on_progress
fuchsia = '\033[38;2;255;00;255m' # color as hex #FF00FF
reset_color = '\033[39m'
# url is url of youtube video to download.
def download_youtube(url):
""" Instantiates YouTube class and downloads selected video. Uses Built-in
pytube.cli function on_progress to show a DOS style progress bar. """
yt = YouTube(url, on_progress_callback=on_progress)
# following line displays title and number of times video has been viewed.
print(f'\n' + fuchsia + 'Downloading: ', yt.title, '~ viewed', yt.views,
'times.')
# creates download and downloads to subdirectory called 'downloads'
yt.streams.first().download('.\\downloads\\')
# displays message verifying download is complete, and resets color scheme
# back to original color scheme.
print(f'\nFinished downloading: {yt.title}' + reset_color)
Display colors were switched because the default progress bar is fairly bright. In event video was previously downloaded the 'Finished downloading:' message will display but the progress bar won't displayed.
Please see this Showing progress in pytube regarding the use of pytube's built-in on_progress function.
# importing YouTube from pytube
import progressbar as progress
from pytube import YouTube
def progress(streams, chunk: bytes, bytes_remaining: int):
contentsize = video.filesize
size = contentsize - bytes_remaining
print('\r' + '[Download progress]:[%s%s]%.2f%%;' % (
'█' * int(size*20/contentsize), ' '*(20-int(size*20/contentsize)), float(size/contentsize*100)), end='')
url = 'https://www.youtube.com/watch?v=qOVAbKKSH10'
yt = YouTube(url, on_progress_callback=progress)
video = yt.streams.get_highest_resolution()
video.download()

Error using checkmouse

I'm trying to use checkmouse in order to undraw something from my window. When someone clicks the button it should undraw the text and write something else. I'm using checkMouse and getX() and getY() to do this but i keep receiving this error that states:
File "C:\Users\User\Documents\python\project2.py", line 71, in panel
if (clicknew.getX()>90 and clicknew.getX()<210) and (clicknew.getY()>35 and clicknew.getY() < 0):
AttributeError: 'NoneType' object has no attribute 'getX'
this code that i have done so far is as follows:
from graphics import *
#creating the game panel window
def panel():
#grey window, with coordinates flipped, with banners etc
win = GraphWin("Start Panel", 300,200)
win.setCoords(0,0,300,200)
win.setBackground("light grey")
#drawing the BoilerMazer banner with text
boilermazer = Rectangle(Point(0,200),Point(300,160))
boilermazer.setFill("white")
boilermazer.draw(win)
#text inside
banner1 = Text(Point(150,180),"BoilerMazer")
banner1.setStyle("bold")
banner1.setSize(20)
banner1.draw(win)
#initial game panel is going to have two buttons and a top scores object
#top score "screen"
toprec = Rectangle(Point(60,140),Point(240,50))
toprec.setFill("white")
toprec.draw(win)
#text inside toprec
topscores = Text(Point(150,130),"TOP SCORES")
topscores.setSize(8)
topscores.draw(win)
border = Text(Point(150,120),"======")
border.draw(win)
bigmac = Text(Point(150,110),"Big Mac 21")
bigmac.setSize(8)
bigmac.draw(win)
tt = Text(Point(150,90),"T.T 23")
tt.setSize(8)
tt.draw(win)
cshell = Text(Point(150,75),"C-Shell 25")
cshell.setSize(8)
cshell.draw(win)
macmac = Text(Point(150,55),"MacMac 27")
macmac.setSize(8)
macmac.draw(win)
#new player button that will eventually be clicked
new1 = Point(90,35)
new2 = Point(210,0)
newrec = Rectangle(new1,new2)
newrec.setFill("chartreuse2")
newrec.draw(win)
#new player button text
newplayer = Text(Point(150,18),"NEW PLAYER")
newplayer.draw(win)
#reset button
resetrec = Rectangle(Point(240,35),Point(300,0))
resetrec.setFill("red")
resetrec.draw(win)
#resettext
reset = Text(Point(270,18),"RESET")
reset.draw(win)
#secondary panel window is the game panel after they click new player
#set up points that we check between for the new player button first
#setting up the checkmouse
clicknew = win.checkMouse()
if (clicknew.getX()>90 and clicknew.getX()<210) and (clicknew.getY()>35 and clicknew.getY() < 0):
newplayer.undraw()
you can find the graphics window here:http://mcsp.wartburg.edu/zelle/python/graphics.py
I don't understand what I'm doing wrong, is there some other method that I'm supposed to be using? Thanks for your help
According to the docs, checkMouse() returns None if no mouse click has been detected priorly. So that seems to be the case.
You could put a loop around the call to checkMouse and keep checking if clicknew is not None and only in that case go on in your program. But maybe there's a better way...
UPDATE:
Example:
while True:
clicknew = win.getMouse()
if clicknew:
break
else:
time.sleep(0.1) # avoid busy waiting
# clicknew is set now => use it

python : bind function to button

this is my python code GUI generated from PAGE 4.6.
I want to create a function which will change the textbox value in real time example
tbCapturedImage.set("test 1").
take a look at
self.btnCapture.bind('<Button-1>', self.Capture_a)
but it cant seems to change the value of the textbox.
self.tbCapturedImage = Text(self.TLabelframe1)
self.tbCapturedImage.place(relx=0.04, rely=0.65, relheight=0.33
, relwidth=0.93)
self.tbCapturedImage.configure(background="white")
self.tbCapturedImage.configure(font="TkTextFont")
self.tbCapturedImage.configure(selectbackground="#c4c4c4")
self.tbCapturedImage.configure(width=206)
self.tbCapturedImage.configure(wrap=WORD)
self.btnCapture = Button(master)
self.btnCapture.place(relx=0.01, rely=0.92, height=45, width=982)
self.btnCapture.configure(activebackground="#d9d9d9")
self.btnCapture.configure(disabledforeground="#a7a4a7")
self.btnCapture.configure(font=font11)
self.btnCapture.configure(text='''Capture Image''')
self.btnCapture.bind('<Button-1>', self.Capture_a)
self.Labelframe1 = LabelFrame(master)
self.Labelframe1.place(relx=0.25, rely=0.48, relheight=0.43
, relwidth=0.74)
self.Labelframe1.configure(relief=GROOVE)
self.Labelframe1.configure(text='''Color Detection''')
self.Labelframe1.configure(width=740)
self.Labelframe2 = LabelFrame(master)
self.Labelframe2.place(relx=0.25, rely=0.05, relheight=0.43
, relwidth=0.35)
self.Labelframe2.configure(relief=GROOVE)
self.Labelframe2.configure(text='''Perspective Transformation''')
self.Labelframe2.configure(width=350)
self.Labelframe3 = LabelFrame(master)
self.Labelframe3.place(relx=0.61, rely=0.05, relheight=0.43
, relwidth=0.38)
self.Labelframe3.configure(relief=GROOVE)
self.Labelframe3.configure(text='''Haar-Like Detection''')
self.Labelframe3.configure(width=380)
def Capture():
tbCapture.Set("test")
def Capture_a(self,event):
self.Capture()
if __name__ == '__main__':
vp_start_gui()
You have to use self and set instead of Set
And probably you should use tbCapturedImage instead of tbCapture
def Capture(self): # self
self.tbCapturedImage.set("test") # self, set and tbCapturedImage
BTW: you can use command= in Button instead of bind
self.btnCapture = Button(master, command=self.Capture)
or
self.btnCapture.configure(command=self.Capture)
command= doesn't send event so method doesn't need argument event

How to manually set the toggle state of wxpython platebutton

I am building an application using platebutton iin wxpython. The problem is that I am not able to manually SetState of the toogle buton. I used SetState(0) but it does not change the state of toggle button. Any help would be great. Thanks. Sample code:
self.infinity= platebutton.PlateButton(self._ribbon,wx.ID_NEW, bmp = wx.Bitmap('infinity.bmp'), pos = (0,0), size = (38,18), style= platebutton.PB_STYLE_NOBG |platebutton.PB_STYLE_TOGGLE)
def OnInfinityToggled(self,event):
if event.GetEventObject().IsPressed():
self.popupmenu = wx.Menu()
Session = self.popupmenu.Append(-1, "Session")
self.Bind(wx.EVT_MENU, self.SessionMenu, Session)
self.PopupMenu(self.popupmenu,(2,23))
else:
pass
def SessionMenu(self, event):
print 5
self.infinity.SetState(0)
self.infinity.Raise()
PLATE_NORMAL = 0
PLATE_PRESSED = 1
PLATE_HIGHLIGHT = 2
SetState(0) means set to normal.
Here's how I managed to toggle state:
btn._ToggleState()
btn._pressed = True
I had the same problem. Playing around I managed to resolve my problem with
button._SetState(ix)
button.Refresh()
where ix = your choice of state.

Resources