I'm trying this:
import os, sys
from Gui import *
import Image as PIL
import ImageTk
class ImageBrowser(Gui):
def __init__(self):
Gui.__init__(self)
self.button = self.bu(command=self.quit, relief=FLAT)
def image_loop(self, dirname='.'):
files = os.listdir(dirname)
for file in files:
try:
self.show_image(file)
print (file)
self.mainloop()
except IOError:
continue
except:
break
def show_image(self, filename):
image = PIL.open(filename)
self.tkpi = ImageTk.PhotoImage(image)
self.button.config(image=self.tkpi)
def main(script, dirname='.'):
g = ImageBrowser()
g.image_loop(dirname)
if __name__ == '__main__':
main(*sys.argv)
I'm getting an error that says:
from Gui import *
ImportError: No module named Gui
I'm assuming "from Gui import *" doesn't work in python 3, does anyone know how to do this in python 3? Thank you so much (:
If you are talking about the Gui module that comes with Swampy, then
in order to use Gui with Python3, you'll need to install the Python3 version of Swampy.
Related
I have the following code that is automating a process in the browser.
At the line pt.click(clicks=3) I can get the text selected in the input box (Chrome). At the line pc.copy() I should copy this text and send it to the variable self.message to be processed. This step is not working.
There are a lot of documents and tutorials on how to do that on Windows and Mac, not in Ubuntu, specially in Ubuntu 22.04.
I am using OS Ubuntu 22.04 and Python 3.10.4.
What am I missing?
from turtle import right
import cv2 as cv
from time import sleep
# Waiting time
print('Waiting 2s')
sleep(2)
import pyautogui as pt
import paperclip as pc
from tkinter import ttk
....
def nav_message(self):
try:
clipPicCenter = pt.locateCenterOnScreen('./clip_pic.png', confidence=0.7)
# print('LocateCenter clip_pic', clipPicCenter)
pt.moveTo(clipPicCenter[0]+48, clipPicCenter[1]-60, duration=self.speed)
pt.click(clicks=3)
sleep(.9)
self.message = pc.copy() //Out PUT - Pyperclip do not have the method copy()
print(self.message)
# pt.click(button='right', clicks=1)
# pos = pt.position()
# pt.moveTo(pos[0]+20, pos[1]-300, duration=self.speed)
# txt = pt.click()
# print(txt)
# self.nav_input_box()
# pt.write(txt)
# txt = pt.hotkey("ctrl", "c") # copy the text (simulating key strokes)
# pt.click(button=right)
except Exception as e:
print ('Exception (nav_green_dot): ', e)
you can use this to copy something to your clipboard
import pyperclip
s1 = "Hello world"
pyperclip.copy(s1)
s2 = pyperclip.paste()
print(s2)
Line 9 you import paperclip as pc. You need to import pyperclip as pc (Note that it starts with py and not pa). The 2 are spelled similar, but your code imports the paperclip library for Django instead of the pyperclip library for managing the clipboard. Heres a codeblock with your fixed imports:
from turtle import right
import cv2 as cv
from time import sleep
# Waiting time
print('Waiting 2s')
sleep(2)
import pyautogui as pt
# this used to be "paperclip"
# "pyperclip" is what you need to import
import pyperclip as pc
from tkinter import ttk
I am essentially repeating a question that was asked (but not answered) in the comments of PyQt: Getting file name for file dropped in app .
What I'd like to be able to do, a la that post, is convert an output from a file drop event in pyqt that currently looks like this:
/.file/id=6571367.661326 into an actual file path (i.e. /.Documents/etc./etc./myProject/fileNeeded.extension)
so that I can make use of the file that made the attempted QDropEvent. how to do this. Any thoughts?
EDIT:
As mentioned below in the comments, this appears to be a platform specific problem. I am running Mac OS X El Capitan (10.11.2)
I figured out the solution after translating Obj-C code found in https://bugreports.qt.io/browse/QTBUG-40449. Note that this solution is only necessary for Macs running OS X Yosemite or later AND not running PyQt5 (i.e. running v.4.8 in my case).
import objc
import CoreFoundation as CF
def getUrlFromLocalFileID(self, localFileID):
localFileQString = QString(localFileID.toLocalFile())
relCFStringRef = CF.CFStringCreateWithCString(
CF.kCFAllocatorDefault,
localFileQString.toUtf8(),
CF.kCFStringEncodingUTF8
)
relCFURL = CF.CFURLCreateWithFileSystemPath(
CF.kCFAllocatorDefault,
relCFStringRef,
CF.kCFURLPOSIXPathStyle,
False # is directory
)
absCFURL = CF.CFURLCreateFilePathURL(
CF.kCFAllocatorDefault,
relCFURL,
objc.NULL
)
return QUrl(str(absCFURL[0])).toLocalFile()
To see this working in a drag and drop situation, see below:
import sys
import objc
import CoreFoundation as CF
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyListWidget(QListWidget):
def __init__(self, parent):
super(MyListWidget, self).__init__(parent)
self.setAcceptDrops(True)
self.setDragDropMode(QAbstractItemView.InternalMove)
def getUrlFromLocalFileID(self, localFileID):
localFileQString = QString(localFileID.toLocalFile())
relCFStringRef = CF.CFStringCreateWithCString(
CF.kCFAllocatorDefault,
localFileQString.toUtf8(),
CF.kCFStringEncodingUTF8
)
relCFURL = CF.CFURLCreateWithFileSystemPath(
CF.kCFAllocatorDefault,
relCFStringRef,
CF.kCFURLPOSIXPathStyle,
False # is directory
)
absCFURL = CF.CFURLCreateFilePathURL(
CF.kCFAllocatorDefault,
relCFURL,
objc.NULL
)
return QUrl(str(absCFURL[0])).toLocalFile()
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.acceptProposedAction()
else:
super(MyListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
super(MyListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
if QString(url.toLocalFile()).startsWith('/.file/id='):
url = self.getUrlFromLocalFileID(url)
links.append(url)
else:
links.append(str(url.toLocalFile()))
for link in links:
self.addItem(link)
else:
super(MyListWidget,self).dropEvent(event)
class MyWindow(QWidget):
def __init__(self):
super(MyWindow,self).__init__()
self.setGeometry(100,100,300,400)
self.setWindowTitle("Filenames")
self.list = MyListWidget(self)
layout = QVBoxLayout(self)
layout.addWidget(self.list)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle("plastique")
window = MyWindow()
window.show()
sys.exit(app.exec_())
I tried another attempt with this
kivy 1.9.0
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.uix.widget import Widget
from simpleOSC import initOSCClient, initOSCServer, closeOSC, \
setOSCHandler, sendOSCMsg
class OscShowcase(BoxLayout):
pass
def __init__(self, **kwargs):
super(OscShowcase, self).__init__(**kwargs)
#self.but_Osc = Button(text='Press to show Osc')
#self.but_Osc.bind(on_release=self.send_Osc)
#self.add_widget(self.but_Osc)
def send_Osc(self, *l):
pass
#sendOSCMsg('/chaine_en_dur/', [2.0])
def sendOSCMsg( address='/print', data=[] ) :
m = OSCMessage()
m.setAddress(address)
for d in data :
m.append(d)
basic_client.send(m)
class OscWidget(GridLayout):
def __init__(self, **kwargs):
super(OscWidget, self).__init__(**kwargs)
class TestOscApp(App):
def build(self):
return OscShowcase()
if __name__ == '__main__':
host = '127.0.0.1'
sport = 9000
rport = 9001
# osc
initOSCClient(host, sport)
initOSCServer(host, rport)
TestOscApp().run()
.kv file
<OscShowcase>:
BoxLayout:
OscWidget:
Button:
text: 'OSC'
pos: (700, 500)
# on_release : sendOSCMsg('')
# sendOSCMsg: '/chaine_en_dur/', [2.0]
# on_release : self.but_Osc.bind()
group: 'OscButton'
on_press: sendOSCMsg('2')
I still get an error "NameError: name 'sendOSCMsg is not defined" when I press the button. Is anybody can help me to understand why? I would like to send osc messages out to Max MSP
Kv Lang has some scopes, you can read more about it here
There are three keywords specific to Kv language:
app: always refers to the instance of your application.
root: refers to the base widget/template in the current rule
self: always refer to the current widget
You can run a method from TestOscApp with app.method_name() and from OscShowcase with root.method_name()
So, just update your kv to call sendOSCMsg from OscShowcase:
on_press: root.sendOSCMsg('2')
I'm really puzzled by this, but the answer is probably quite simple and just can't see it:
I have a series of python modules that work fine from within the python interpreter, but nothing happens when running from a GUI situation. I've tried creating a .desktop file, adding shebangs, changing permissions to 777 and renaming to .pyw for all the modules. A single test module works fine on its own, so I know that it's not a typo error.
If I click the main module .pyw file and click 'Run' from the system dialogue nothing happens at all. Similarly the .py file (and the .desktop via menu)... nothing. Here is the start of my code:#
#!/usr/bin/python3
import tkinter as tk, imp, sys
root = tk.Tk()
msg = tk.messagebox
sdg = tk.simpledialog
import capitaliser_cfg as cfg, fileio as io
imp.reload(cfg) ; imp.reload(io)
### GO AND GET COUNTY LIST ####
# Nb: attach to config for simplicity
cfg.counties = io.getfilelist("counties.txt", "London")
if not type(cfg.counties)==list:
k = msg.showerror(cfg.version, cfg.counties)
root.destroy()
root.mainloop()
### GO AND GET DICTIONARY ####
cfg.tempdict = [[],[],[]]
cfg.spelldict = io.getdictionary("addressdict.txt","roda","Road")
if not type(cfg.spelldict)==dict:
k = msg.showerror(cfg.version, cfg.spelldict)
root.destroy()
root.mainloop()
import thinbutton as tb, labelradio as lr, fieldblock as fb, bigbutton as bb
import textblock as tx, padding as pd, widget_tools as wt
import capitaliser_mth as mth
import capitaliser_bnd as bnd
imp.reload(tb) ; imp.reload(lr) ; imp.reload(fb) ; imp.reload(bb)
imp.reload(tx) ; imp.reload(pd) ; imp.reload(wt) ;
imp.reload(mth)
imp.reload(bnd)
If I put k = msg.showerror("xxxx","yyyy") after the line sdg = tk.simpledialog, still nothing happens which leads me to believe that tkinter is not loading for some reason.
Any ideas anyone ?
For Python 2 try:
import tkMessageBox
import tkSimpleDialog
msg = tkMessageBox
sdg = tkSimpleDialog
or simpler:
import tkMessageBox as msg
import tkSimpleDialog as sdk
For Python 3 try:
from tkinter import messagebox
from tkinter import simpledialog
msg = messagebox
sdg = simpledialog
or simpler:
from tkinter import messagebox as msg
from tkinter import simpledialog as sdg
After freezing my Python programs using cx_freeze, I tried to run exe file created but its not running.
PhoneBook.py
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import *
class PhoneBook:
i=0;
def __init__(self):
loader = QUiLoader();
file = QFile("PhoneBook.ui");
file.open(QFile.ReadOnly);
self.ui = loader.load(file);
file.close();
self.ui.setWindowIcon(QIcon('web.png'));
self.ui.pushButton.clicked.connect(self.add);
self.ui.pushButton_2.clicked.connect(self.load);
def __del__ ( self ):
self.ui = None;
def add(self):
loader1 = QUiLoader();
file1 = QFile("Add.ui");
file1.open(QFile.ReadOnly);
self.ui2 = loader1.load(file1);
file1.close();
self.ui2.show();
self.ui2.pushButton.clicked.connect(self.get);
def show(self):
self.ui.show();
def clear1(self):
self.ui.lineEdit.clear();
def get(self):
name1 = self.ui2.lineEdit.text();
name2 = self.ui2.lineEdit_2.text();
f = open('data','a' );
f.write(name1);
f.write('#');
f.write(name2);
f.write('\n');
f.close();
self.load();
self.ui2.close();
def load(self):
f = open('data', 'r');
for i in range(0, 10):
string = f.readline();
l=len(string);
print(string);
print(l);
for c in range(0, l-1):
if string[c]=="#":
break;
print(c);
name1=string[0:c];
name2=string[c+1:l-1];
self.ui.tableWidget.setItem(i, 0, QTableWidgetItem(name1));
self.ui.tableWidget.setItem(i, 1, QTableWidgetItem(name2));
i =i+1;
def sort(self):
f=open('data', 'r');
f.readlines().sort();
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setApplicationName('PhoneBook Application')
w = PhoneBook();
w.show();
QObject.connect(app, SIGNAL('lastWindowClosed()'), app,SLOT('quit()'))
sys.exit(app.exec_())
setup.py
import sys
from cx_Freeze import setup,Executable
includefiles = ['Add.ui', 'PhoneBook.ui', 'data', 'web.png']
includes = ["re"]
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(name="PhoneBook", version="3.0",description="Test",options = {'build_exe': {'include_files':includefiles, 'includes' : includes}
Is it because I am using QUILoader ? However on executing the Python code directly its showing correct results. Please help me.
From the docs its seems that you must include atexit
cxfreeze yourapp.py --target-dir dist --base-name Win32GUI --include-modules atexit,PySide.QtNetwork --icon yourapptaskgroup.ico
The site specifically mentions that if you don't include atextit , the installer is not going to work
“atexit” must be included in —include-modules, otherwise the generated exe will fail.
Link to the knowledge base article
Another cause of error was that cx-freeze was using some dlls from PyQt.
And the dlls are not same in pyside and pyqt, so if you have pyqt insalled i would suggest adding PyQt4 to the excludes
excludes=['PyQt4', 'tcl', 'tk', 'ttk', 'tkinter', 'Tkconstants', 'Tkinter', "collections.sys", "collections._weakref"]