socket sendto not working on Android (kivy, buildozer) - python-3.x

I am writing a script in kivymd to toggle an LED which is connected to a microcontroller. The script is supposed to send a socket UDP msg to the MCU server, which includes a command to toggle the LED. The script works fine on windows, and the building with buildozer is successful (although not shown in this script but I tried another version to simply print hello world to an MDLabel and it worked) but whenever I press the btn_led on Android, the application shuts down. Any ideas why this is happening and how to fix it?
from kivymd.app import MDApp
from kivymd.uix.button import MDFlatButton
from kivy.uix.screenmanager import Screen
import socket
class TableApp(MDApp):
def build(self):
# Add Widgets
screen = Screen()
btn_led = MDFlatButton(text="Toggle LED", on_release=self.toggle_led,
pos_hint={"center_x": 0.5, "center_y": 0.5})
screen.add_widget(btn_led)
return screen
def toggle_led(self, event):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b"LED", ("10.0.0.167", 1111))
s.close()
TableApp().run()

I just learned that the buildozer.spec file contains permissions which can be configured to include INTERNET. I uncommented the permissions line which contains INTERNET by default and everything worked like a charm!

Related

How to set Window focus on an easygui message box

I am building a very simple python project that will allow the user to read a message in a box and then click OK. This will part of a larger program.
The issue is that when I run it in Spyder, the message box ends up behind all other windows. How do I make it be the focus and open in front of all other windows? I am running a Windows 11 computer.
I call the below function from another python script.
# import libraries
# sys / os to change working directory
import sys
import os
# easygui for message boxes
from easygui import *
# Create function to set working directory
def setworkdir():
uni_code = fileopenbox()
print(uni_code)
# Create Welcome Box
def openMsgBox():
msgbox("Welcome to DocPhoto. Click on Ok to get started")
setworkdir()
The script to call it:
from docFunctions import openMsgBox
openMsgBox()
I have seen answers where the programmer is trying to do this in tkinter, but I'm not using tkinter. Is there a way to do it without tkinter?

Trying to convert python file to .exe (contains tkinter code)

Trying to convert my code to .exe file so that other users can make use of it.
The purpose of this code is to get an interface where the user can enable/disable LAN connection in a single click.
Kindly 'run as administrator' you IDLE to make this code work.
import tkinter as tk
import subprocess as sub
import os
WINDOW_SIZE = "350x100"
root = tk.Tk()
root.title("Windows Adapter Toggler")
root.geometry(WINDOW_SIZE)
#to execute bash command right from python script
tk.Button(root, text="DISABLE Internet", command=lambda: sub.call('netsh
interface set interface name="Ethernet" admin=DISABLED')).pack()
tk.Button(root, text="ENABLE Internet", command=lambda: sub.call('netsh
interface set interface name="Ethernet" admin=ENABLED')).pack()
#os.system(bashCommand)
root.mainloop()
SideNote:
1.Will work if your ethernet port name is 'ethernet',if something else then change the name in the code.Will implement this 'changing name of port'feature later in the code.
2.Already tried converting with pyinstaller and py2exe but didn't happen.

PyQt5 GUI freeze caused by Windows focus-follows-mouse

When Windows focus-follows-mouse-without-raising-the-window is enabled by either of the two methods linked to below, I consistently get PyQt5 GUI 'freezes' where you have to type any character in the terminal that you ran python from in order to unfreeze the GUI; complete description and test case (Windows 10, Python 3.6.1, PyQt5) is here: pyqt5 click in terminal causes GUI freeze
To enable the focus-follows-mouse-without-raise behavior, try either of these - they both work in Windows 10:
downloadable program ('X-Mouse' though that name is used by other programs):
https://joelpurra.com/projects/X-Mouse_Controls/
registry hack description:
https://sinewalker.wordpress.com/2010/03/10/ms-windows-focus-follows-mouse-registry-hacks/
So - a few questions:
can anyone reproduce the issue? It seems 100% reproducible for me, but it would be great to hear the same from someone else.
is there a way to change the python code to detect-and-circumvent focus-follows-mouse, or just to be immune to it, i.e. maybe by ensuring the GUI application always takes focus back again when you - for example - click in a dialog or qmessagebox owned by the main GUI window, or by some other means? (Is the object hierarchy set up optimally, and if not, maybe this could all be resolved by correcting the ownership structure?)
The brute-force solution seems to work, though I'd like to leave this question open to see if someone knows of a more optimal solution; it took a fair amount of searching to figure out the right way; mainly by taking a look a the open-source code for X-Mouse. Basically, this method takes effect immediately, whereas the registry hack doesn't take effect until reboot.
New version of pyqt_freeze_testcase.py (the file from the referenced stackoverflow question); the changes are only additions, noted between lines of hash marks:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
####################### added begin:
import win32gui
import win32con
####################### added end
# import the UI file created with pyuic5
from minimal_ui import Ui_Dialog
class MyWindow(QDialog,Ui_Dialog):
def __init__(self,parent):
QDialog.__init__(self)
self.parent=parent
self.ui=Ui_Dialog()
self.ui.setupUi(self)
################################# added begin:
self.initialWindowTracking=False
try:
self.initialWindowTracking=win32gui.SystemParametersInfo(win32con.SPI_GETACTIVEWINDOWTRACKING)
except:
pass
if self.initialWindowTracking:
print("Window Tracking was initially enabled. Disabling it for now; will re-enable on exit.")
win32gui.SystemParametersInfo(win32con.SPI_SETACTIVEWINDOWTRACKING,False)
################################# added end
def showMsg(self):
self.really1=QMessageBox(QMessageBox.Warning,"Really?","Really do stuff?",
QMessageBox.Yes|QMessageBox.No,self,Qt.WindowTitleHint|Qt.WindowCloseButtonHint|Qt.Dialog|Qt.MSWindowsFixedSizeDialogHint|Qt.WindowStaysOnTopHint)
self.really1.show()
self.really1.raise_()
if self.really1.exec_()==QMessageBox.No:
print("nope")
return
print("yep")
################################## added begin:
def closeEvent(self,event):
if self.initialWindowTracking:
print("restoring initial window tracking behavior ("+str(self.initialWindowTracking)+")")
win32gui.SystemParametersInfo(win32con.SPI_SETACTIVEWINDOWTRACKING,self.initialWindowTracking)
################################## added end
def main():
app = QApplication(sys.argv)
w = MyWindow(app)
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

QLineEdit.setText only works once in function

I'm currently trying to program for my bachelor thesis. The main part works, so now I want to implement a user interface. I watched some tutorials and worked via trial and error, and my user interface also works. So far so good. But yesterday I changed a small thing and that doesn't do what i want. I have a button saying "start program", and a line-edit where i want to display the current status. My code is:
import sys
from PyQt4 import QtGui
from theguifile import Ui_MainWindow
import otherfile
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
self.ui.mybutton.clicked.connect(self.runprogram)
def runprogram(self):
self.ui.mylineedit.setText('Running') # doesnt work
try:
otherfile.therealfunction() # works
except ErrorIwanttocatch:
self.ui.mylineedit.setText('thisErrorhappened') # works
else:
self.ui.mylineedit.setText('Success') # works
app = QtGui.QApplication(sys.argv)
window = Main()
sys.exit(app.exec_())
Everything works as I want except from lineedit.setText('Running'). What I want is that "Running" is displayed while otherfile.therealfunction is working. I guess I have to update the line-edit somehow? But until now I didn't figure out how I can do that. I also set the line-edit readonly because I don't want the user to be able to change it, so maybe that's a problem? I thought readonly would only affect what the user can do.
I am using Python3 and PyQt4 with Qt Designer.
Calling otherfile.therealfunction() will block all ui updates until the function completes. You can try forcing immediate ui updates like this:
def runprogram(self):
self.ui.mylineedit.setText('Running')
QtGui.qApp.processEvents()

Custom sound in a message dialog box in wxPython

I was wondering is there any way to get a custom sound to play as soon as a message dialog box comes up? my only restriction is that I can only use wxPython for this, for arguments sake lets call the sound file 'music.wav' Here is my code so far (ignore the stuff about playing with text, that was me creating a dummy GUI for it to load):
import wx
import time
import winsound, sys
class ButtonTest(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,None,id,'Button/Text test frame',size=(800,500))
panel=wx.Panel(self)
button=wx.Button(panel, label='Exit', pos=(200,50), size=(-1,-1))
self.Bind(wx.EVT_BUTTON, self.closer, button)
self.Bind(wx.EVT_CLOSE, self.wincloser)
ape=wx.StaticText(panel, -1, 'This text is STATIC', (200,80))
ape.SetFont(wx.Font(25, wx.SWISS, wx.ITALIC, wx.BOLD, True,'Times New Roman'))
def beep(sound):
winsound.PlaySound('%s.wav'%sound, winsound.SND_FILENAME)
#wx.FutureCall(1000, beep('C:\Users\Chris\Desktop\music'))
box=wx.MessageDialog(None,'Is this a good test?','Query:',wx.ICON_ERROR)
answer=box.ShowModal()
box.Destroy
beep('C:\Users\Chris\Desktop\music')
def closer(self,event):
self.Close(True)
def wincloser(self,event):
self.Destroy()
if __name__=='__main__':
app=wx.PySimpleApp()
frame=ButtonTest(None,id=-1)
frame.Show()
app.MainLoop()
For Windows, there's winsound, which is built in to Python. Otherwise, you'll need an external library like pyAudio or Snack Sound. See also Play a Sound with Python

Resources