So, I'm quite new to using python and I wanted to learn more about it so I decided to download a sticky note program from the internet (Rhinote) and study / modify it to use a menu bar instead of control commands to execute the methods. I also modified it to work with Python 3.x instead of Python 2.
The problem I'm coming up with after modifying it with the menu bar is that it creates the file but doesn't actually write to it. I've been trying to fix this for a while now so any help is appreciated.
Here is the code I have currently:
from tkinter import *
import tkinter.filedialog, tkinter.messagebox
import os
from os import system
# the root window:
def Sticky():
r = Tk()
r.option_add('*font', '{Helvetica} 11')
t = Text(r, bg = '#f9f3a9', wrap = 'word', undo = True)
t.focus_set()
t.pack(fill = 'both', expand = 1)
r.geometry('220x235')
r.title('Note')
text = TextWidget()
m = tkinter.Menu(r)
m.add_command(label="+", command=text.new_window)
m.add_command(label="Save", command=text.save_file)
m.add_command(label="Save As", command=text.save_file_as)
m.add_command(label="Open", command=text.open_file)
r.config(menu=m)
r.mainloop()
# the text widget, and all of its functions:
class TextWidget(Text):
def __init__(self):
Text.__init__(self)
self.filename = ''
self._filetypes = [
('Text', '*.txt'),
('All files', '*'),
]
def save_file(self, whatever = None):
if (self.filename == ''):
self.save_file_as()
else:
f = open(self.filename, 'w')
f.write(self.get('1.0', 'end'))
f.close()
tkinter.messagebox.showinfo('FYI', 'File Saved.')
def save_file_as(self, whatever = None):
self.filename = tkinter.filedialog.asksaveasfilename(defaultextension='.txt',
filetypes = self._filetypes)
f = open(self.filename, 'w')
f.write(self.get('1.0', 'end'))
f.close()
tkinter.messagebox.showinfo('FYI', 'File Saved')
def open_file(self, whatever = None, filename = None):
if not filename:
self.filename = tkinter.filedialog.askopenfilename(filetypes = self._filetypes)
else:
self.filename = filename
if not (self.filename == ''):
f = open(self.filename, 'r')
f2 = f.read()
self.delete('1.0', 'end')
self.insert('1.0', f2)
f.close()
self.title('Sticky %s)' % self.filename)
def new_window(self):
Sticky()
def help(whatever = None):
tkinter.messagebox.showinfo('Help', message = '''
Help
''')
# make it so:
if __name__ == '__main__':
Sticky()
And here is the Rhinote program I'm trying to modify:
from tkinter import *
import tkinter.filedialog, tkinter.messagebox
import os
from os import system
# the root window:
def Rhinote():
r = Tk()
r.option_add('*font', '{Helvetica} 11')
t = TextWidget(r, bg = '#f9f3a9', wrap = 'word', undo = True)
t.focus_set()
t.pack(fill = 'both', expand = 1)
r.geometry('220x235')
r.title('Rhinote')
r.mainloop()
# the text widget, and all of its functions:
class TextWidget(Text):
def save_file(self, whatever = None):
if (self.filename == ''):
self.save_file_as()
self.master.title('Rhinote %s' % self.filename)
else:
f = open(self.filename, 'w')
f.write(self.get('1.0', 'end'))
f.close()
self.master.title('Rhinote %s' % self.filename)
tkinter.messageb ox.showinfo('FYI', 'File Saved.')
def save_file_as(self, whatever = None):
self.filename = tkinter.filedialog.asksaveasfilename(filetypes = self._filetypes)
f = open(self.filename, 'w')
f.write(self.get('1.0', 'end'))
f.close()
tkinter.messagebox.showinfo('FYI', 'File Saved')
def open_file(self, whatever = None, filename = None):
if not filename:
self.filename = tkinter.filedialog.askopenfilename(filetypes = self._filetypes)
self.master.title('Rhinote %s' % self.filename)
else:
self.filename = filename
self.master.title('Rhinote %s' % self.filename)
if not (self.filename == ''):
f = open(self.filename, 'r')
f2 = f.read()
self.delete('1.0', 'end')
self.insert('1.0', f2)
f.close()
self.master.title('Rhinote %s)' % self.filename)
def new_window(self, event):
Rhinote()
def printfile(self, whatever = None):
f = open(self.printfilename, 'w')
f.write(self.get('1.0', 'end'))
f.close
# 'enscript' formats the text; lpr sends it to the default printer;
# enscript's -B option suppresses page headers.
system('enscript -B --word-wrap $HOME/.Rhinoteprintfile > lpr &')
def help(self, whatever = None):
tkinter.messagebox.showinfo('Rhinote Help', message = '''
Editing Commands
Ctrl-x : Cut selected text
Ctrl-c : Copy selected text
Ctrl-v : Paste cut/copied text
Ctrl-Z : Undo
Ctrl-Shift-z : Redo
File Commands
Ctrl-o : Open file
Ctrl-s : Save current note
Ctrl-a : Save current note as <filename>
Ctrl-p : Print current note
Ctrl-n : Open new Rhinote
General
Ctrl-h : Display this help window
Rhinote version 0.7.4
Free Software distributed under the GNU General Public License
http://rhinote.tuxfamily.org
''')
def __init__(self, master, **kw):
Text.__init__(self, master, **kw)
self.bind('<Control-n>', self.new_window)
self.bind('<Control-N>', self.new_window)
self.bind('<Control-o>', self.open_file)
self.bind('<Control-O>', self.open_file)
self.bind('<Control-s>', self.save_file)
self.bind('<Control-S>', self.save_file)
self.bind('<Control-a>', self.save_file_as)
self.bind('<Control-A>', self.save_file_as)
self.bind('<Control-p>', self.printfile)
self.bind('<Control-P>', self.printfile)
self.bind('<Control-h>', self.help)
self.bind('<Control-H>', self.help)
self.master = master
self.filename = ''
self.printfilename = os.environ['HOME']+'/.Rhinoteprintfile'
self._filetypes = [
('Text/ASCII', '*.txt'),
('Rhinote files', '*.rhi'),
('All files', '*'),
]
# make it so:
if __name__ == '__main__':
Rhinote()
It was nice that you changed to using menu, but there is one thing you forgot, the Text that's showing onscreen isn't the one named text, it was this while you're retrieving the data from text which is empty because it's covered by t and it wasn't even packed:
t = Text(r, bg = '#f9f3a9', wrap = 'word', undo = True)
t.focus_set()
t.pack(fill = 'both', expand = 1)
Since you used focus_set on it which will be above all other widgets. Just to say simple, you can change your program to something like this, which you wouldn't even need the text.
from tkinter import *
import tkinter.filedialog, tkinter.messagebox
import os
from os import system
# the root window:
def Sticky():
r = Tk()
r.option_add('*font', '{Helvetica} 11')
t = Text(r, bg = '#f9f3a9', wrap = 'word', undo = True)
t.focus_set()
t.pack(fill = 'both', expand = 1)
r.geometry('220x235')
r.title('Note')
TextWidget(t) # pass along t, your Text
m = tkinter.Menu(r)
m.add_command(label="+", command=text.new_window)
m.add_command(label="Save", command=text.save_file)
m.add_command(label="Save As", command=text.save_file_as)
m.add_command(label="Open", command=text.open_file)
r.config(menu=m)
r.mainloop()
# the text widget, and all of its functions:
class TextWidget:
def __init__(self, text):
self.text = text # pass the text widget
self.filename = ''
self._filetypes = [
('Text', '*.txt'),
('All files', '*'),
]
def save_file(self, whatever = None):
if (self.filename == ''):
self.save_file_as()
else:
f = open(self.filename, 'w')
f.write(self.text.get('1.0', 'end')) # change every 'self' that refers to the Text, to self.text
f.close()
tkinter.messagebox.showinfo('FYI', 'File Saved.')
def save_file_as(self, whatever = None):
self.filename = tkinter.filedialog.asksaveasfilename(defaultextension='.txt',
filetypes = self._filetypes)
f = open(self.filename, 'w')
f.write(self.text.get('1.0', 'end'))
f.close()
tkinter.messagebox.showinfo('FYI', 'File Saved')
def open_file(self, whatever = None, filename = None):
if not filename:
self.filename = tkinter.filedialog.askopenfilename(filetypes = self._filetypes)
else:
self.filename = filename
if not (self.filename == ''):
f = open(self.filename, 'r')
f2 = f.read()
self.text.delete('1.0', 'end')
self.text.insert('1.0', f2)
f.close()
self.text.title('Sticky %s)' % self.filename)
def new_window(self):
Sticky()
def help(whatever = None):
tkinter.messagebox.showinfo('Help', message = '''
Help
''')
# make it so:
if __name__ == '__main__':
Sticky()
Since TextWidget is a Text subclass, you should just use it wherever the original program uses the latter. To make that possible, it needs to properly initialize its super class.
Fortunately, not much needs to be changed to do that and use it correctly.
Below are portions of your code that need to be changed:
from tkinter import *
import tkinter.filedialog, tkinter.messagebox
import os
from os import system
# the root window:
def Sticky():
r = Tk()
r.option_add('*font', '{Helvetica} 11')
text = TextWidget(r, bg='#f9f3a9', wrap='word', undo=True) # create subclass here (and
# call it text instead of t)
text.focus_set()
text.pack(fill='both', expand=1)
r.geometry('220x235')
r.title('Note')
m = tkinter.Menu(r)
m.add_command(label="+", command=text.new_window)
m.add_command(label="Save", command=text.save_file)
m.add_command(label="Save As", command=text.save_file_as)
m.add_command(label="Open", command=text.open_file)
r.config(menu=m)
r.mainloop()
# the text widget, and all of its functions:
class TextWidget(Text):
def __init__(self, *args, **kwargs):
Text.__init__(self, *args, **kwargs) # pass all args to superclass
self.filename = ''
self._filetypes = [
('Text', '*.txt'),
('All files', '*'),
]
def save_file(self, whatever=None):
REST OF YOUR CODE, UNCHANGED, GOES HERE...
Related
How do i get the return value filename in the button_explore ?
Here is my code
def browseFiles():
filename = filedialog.askdirectory(initialdir = "/",title = "Select a File")
label_file_explorer.configure(text="File Opened: "+filename)
button_re = Button(window,text = "Browse Files",command = browseFiles)
I want to get the value of filename in command :
button_explore = Button(window,text = " Ok ",command = ??? )
I have an issue with my program.
Whenever I encrypt multiple files, it works flawlessly; when I decrypt the files however, it fails pretty hard. No errors or anything.
The issue is just;
Only one file decrypts, no more. The rest of the files do look decrypted, but at the same time ?not?
Here is an example image of what shows when I decrypted a text file with pi to 1m digits. This only happens when decrypting multiple files.
Finally, here is the code. Big thanks to anyone willing to be helpfull!!! :)
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
import sys
import os.path
from tkinter import *
import tkinter.filedialog as fd
from tkinter import ttk
from tkinter import messagebox
from PIL import ImageTk,Image
from os import startfile
# Just some path defining stuff
user_profile = os.environ['USERPROFILE']
user_desktop = user_profile + "\\Documents"
os.chdir(sys.path[0])
save_path = f'{sys.path[0]}/TestEncrypted'.replace("\\","/")
save_path2 = f'{sys.path[0]}/TestDecrypted'.replace("\\","/")
# Create directories for encrypted/decrypted files
try:
os.mkdir(save_path)
except:
print(f'Directory: {save_path} already exists')
try:
os.mkdir(save_path2)
except:
print(f'Directory: {save_path2} already exists')
def padkey(key):
global oldkey
oldkey = key
while len(key)% 16 != 0:
key+= " "
return key
def encrypt1():
"""
Loops over files for encryption.
"""
newkey = padkey('testpass').encode('UTF-8')
cipher = AES.new(newkey,AES.MODE_CBC)
# Create for loop here!!!
filez = fd.askopenfilenames(parent=root, title='Choose files to encrypt',initialdir = user_desktop)
for filename in filez:
try:
with open(filename, 'rb') as f:
rfile = f.read()
f.close()
except:
messagebox.showerror("ITExtra Popup", "You didn't select a file")
ciphertext = cipher.encrypt(pad(rfile, AES.block_size))
encryptfilename = filename.split('/')[-1]+'.ENCRYPTED'
completeName = os.path.join(save_path, encryptfilename).replace("\\","/")
print(completeName)
with open(completeName,'wb') as c_file:
c_file.write(cipher.iv)
c_file.write(ciphertext)
c_file.close()
label2=Label(root,text=(save_path+"/"+encryptfilename).replace('\\','/').lower(),font='Helvetica 13 bold italic',fg='BLUE',bg='black').place(relx=0,rely=0.88)
return
def decrypt1():
"""
Loops over files for decryption.
"""
faildec = 0
succdec = 0
filez2 = fd.askopenfilenames(parent=root, title='Choose files to decrypt',initialdir = save_path)
for decryptfilename in filez2:
newkey = padkey('testpass').encode('UTF-8')
# Decrypt file
try:
with open(decryptfilename,'rb') as c_file:
iv = c_file.read(16)
ciphertext = c_file.read()
c_file.close()
except:
faildec +=1
cipher = AES.new(newkey,AES.MODE_CBC, iv)
rfile = unpad(cipher.decrypt(ciphertext),AES.block_size)
# Input extension and save file
filename = decryptfilename.split('/')[-1].replace('.ENCRYPTED', '')
completeName2 = os.path.join(save_path2, filename)
with open(completeName2, 'wb') as writefile:
writefile.write(rfile)
writefile.close()
label2=Label(root,text=(save_path2+"/"+filename).replace("\\","/").lower(),font='Helvetica 10 bold italic',fg='BLUE',bg='black').place(relx=0,rely=0.88)
succdec +=1
response2 = messagebox.askyesno("ITExtra Popup", f"""Do you want to open the 'Decrypted' directory?\n{save_path2}
Successful decryptions = {succdec}
Failed decryptions = {faildec}
""")
if response2 == 1:
startfile(save_path2)
return
print(sys.path[0])
print(save_path)
print(save_path2)
print(user_desktop)
root = Tk()
w = 850 # width for the Tk root
h = 310 # height for the Tk root
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
x = (ws/2) - (w/2)
y = (hs/3) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
frame1=LabelFrame(root,bd=0,bg='#000000')
but1 = Button(frame1, text="ENCRYPT file", padx=30, pady=10, bg="#1f1f1f",fg="red",font='Helvetica 15 bold', command=encrypt1,relief=FLAT)
but2 = Button(frame1, text="DECRYPT file", padx=30, pady=10, bg="#1f1f1f",fg="green",font='Helvetica 15 bold', command=decrypt1,relief=FLAT)
but1.grid(row=2,column=0,padx=1,pady=5) # Encrypt FILE #
but2.grid(row=2,column=2,pady=5) # Decrypt FILE #
frame1.place(relx=0.20,rely=0.5)
root.mainloop()
Edit
Removed except statements for debugging purposes.
I am working on a program that allows the user to select a file using one button:
def select_file(self):
filename = tkinter.filedialog.askopenfilename(initialdir=".")
infile = open(filename, "r")
and another button, labeled count occurrences, should read the txt file into a string to search for what the user entered:
def count_occurrences(self):
user_file = open(infile, "r")
txt_file = user_file.read()
# (omitted the code for counting occurrences for the sake of relevance)
I am unsure which function the problem lies in or if it is both.
After clicking the "select file" button, a directory name shows in the label but when I click the "count occurrences" button after entering the search text, I get the error:
"user_file = open(filename, "r") FileNotFoundError: [Errno 2] No such file or directory: ''
Any help would be appreciated, thanks!
I am not sure what is your project code, but here is the solution:
from tkinter import *
from tkinter import ttk, filedialog
#import io
class ReadFileApp:
def __init__(self, master):
self.label = ttk.Label(master, text = "How Read a File Content!")
self.label.grid(row = 0, column = 0, columnspan = 2)
ttk.Button(master, text = "Open File",
command = self.select_file).grid(row = 2, column = 0)
ttk.Button(master, text = "Print the Content",
command = self.count_occurrences).grid(row = 2, column = 1)
def select_file(self):
filename = filedialog.askopenfilename(initialdir=".")
self.infile = open(filename, "r")
#self.infile = io.TextIOWrapper(self.infile, encoding='utf8', newline='')
print(self.infile.name)
def count_occurrences(self):
with open(self.infile.name, 'r') as myfile:
txt_file=myfile.read().replace('\n', '')
print(txt_file)
def main():
main = Tk()
app = ReadFileApp(main)
main.mainloop()
if __name__ == "__main__": main()
this code should work perfectly fine.
your problem was:
The local variable infile is not visible to other functions
The filedialog function returns an io.TextWrapper type, so you need to get the path as a string by calling infile.name
I am building a little Python 3.6.5 tool that takes in an XML document and outputs all its XPaths. It works well, however I need to distribute it in EXE form. I am running on Win10 and only need to provide to Win10 users.
My main code is;
from tkinter import filedialog
from tkinter import *
from pathlib import Path
import winsound
from lxml import etree
import csv
root = Tk()
root.geometry("250x200")
root.resizable(0, 0)
class gui:
def __init__(self, master):
self.master = master
master.title("XGen")
self.welcome = Label(master, text="Welcome to")
self.welcome.config(font=("Arial", 10))
self.welcome.pack()
self.header = Label(master, text="The XPath Generator")
self.header.config(font=("Arial", 16))
self.header.pack()
self.description = Label(master, text="This Tool Takes in an XML Document\nand Provides all its XPaths")
self.description.config(font=("Arial", 10))
self.description.pack()
self.greet_button = Button(master, text="Select Input XML", command=self.greet)
self.greet_button.pack()
self.reportFilename = Label(master, text="")
self.reportFilename.pack()
self.reportProgress = Label(master, text="")
self.reportProgress.pack()
# self.close_button = Button(master, text="Close", command=master.quit)
# self.close_button.pack()
def greet(self):
print("File Selection Started")
from_file_path = filedialog.askopenfilename(initialdir="/",
title="Select file",
filetypes=(("XML Files", "*.xml"), ("all files", "*.*")))
from_file_path_split = Path(from_file_path).parts
to_file_path = ''
if from_file_path is '':
self.reportFilename.config(text="You Did not Select a File")
print("No File Selected. File Selection Ended")
else:
self.reportFilename.config(text="You Selected " + from_file_path_split[-1])
print("From File Path = " + from_file_path)
print("File Name = " + from_file_path_split[-1])
to_file_path = filedialog.asksaveasfilename(initialdir=from_file_path,
title="Save As",
filetypes=(("CSV Files", "*.csv"), ("all files", "*.*")))
if to_file_path is '' or to_file_path == 'Null':
self.reportProgress.config(text="Please select a Save Location")
# elif to_file_split[-1][:4] == "xsd":
else:
to_file_split = Path(to_file_path).parts
to_file_name = to_file_split[-1]
print("Filename = " + to_file_name)
to_file_extension = to_file_split[-1][-4:]
print("Last 4 chars = " + to_file_extension)
if to_file_extension == ".csv":
pass
else:
to_file_path = to_file_path + ".csv"
# to_file_name = to_file_path
print("To File Path = " + to_file_path)
if from_file_path == '' or to_file_path == '' or to_file_path == 'Null':
self.reportProgress.config(text="Please Select a Valid XML File")
winsound.PlaySound("SystemExclamation", winsound.SND_ALIAS)
print("Bad File, Try Again")
else:
out(from_file_path, to_file_path)
self.reportProgress.config(text="Generated " + Path(to_file_path).parts[-1])
print("XGen Complete")
def out(in_path, out_path):
with open(in_path, 'r') as source_file:
xml = source_file.read()
root = etree.fromstring(xml)
tree = etree.ElementTree(root)
line = ['XPath', 'Attribute Name', 'Current Data']
if out_path is None:
return 1
else:
pass
with open(out_path, 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
csv_writer.writerow(line)
for e in root.iter():
path = tree.getpath(e)
list_of_attributes = []
nodes = root.xpath(path)
for node in nodes:
attrs = []
for att in node.attrib:
attrs.append(("#" + att, node.attrib[att]))
list_of_attributes.append(attrs)
for attributes in list_of_attributes:
line = [path, None]
csv_writer.writerow(line)
if len(attributes) == 0:
pass
else:
for x in range(len(attributes)):
xpath = path + attributes[x][0]
current_data = (attributes[x][1])
attribute_name = attributes[x][0]
line = [xpath, attribute_name, current_data]
csv_writer.writerow(line)
my_gui = gui(root)
root.mainloop()
(Please forgive the messy code! I do intend to clean it up for the next version!)
setup.py contains the following;
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
executables = [
Executable('xin.py', base=base)
]
setup(name='XGen',
version='0.1',
description='XGen',
executables=executables
)
This does allow the program to build an EXE, however when that EXE runs, it returns this error.
I have been looking everywhere for solutions.
I found a suggestion that uninstalling all versions of Python then installing just one might work, but no joy.
I have previously tried Py2exe but that does not work either.
I found another suggestion that the PATH could be incorrect, so checked and everything seems correct there too.
As suggested by the error text, I also tried checking that tkinter is properly installed. Not only can this program run through Python, but also IDLE lets me import tkinter.
What could be causing cx_Freeze to throw this error?
Thanks!
The location of the TK DLLs needs to be added to the setup.py. On Windows 10, this might be in the root of C: or in C:\Users\[username]\AppData\Local\Programs\Python\Python36-32/DLLs. Add a variable to store that path, then make it a raw string with a leading r.
import os
import sys
from cx_Freeze import setup, Executable
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
syspath = r"C:\Users\[username]\AppData\Local\Programs\Python\Python36-32/DLLs"
buildOptions = dict(
packages=[],
excludes=[],
include_files=[syspath + '/tcl86t.dll', syspath + '/tk86t.dll']
)
executables = [
Executable('xin.py', base=base)
]
setup(name='XGen',
version='0.1',
options=dict(build_exe=buildOptions),
description='XGen',
executables=executables
)
Many thanks to MrLeeh and DeePak M. Birajdar!
I had the same problem, but it turned out that I had missed some folders to be included in the final build.
For example, my code, at the init level, reads some JSON files from a folder (named 'DataBase') and I did not include the folder in the build.
this is my code:
import sys
from cx_Freeze import setup, Executable
base = None
application_title = 'Myapp'
main_python_file = 'main.py'
if sys.platform == 'win32':
base = 'Win32GUI'
includes = []
include_files = ['DataBase']
setup(name=application_title, version='1',
options={'build_exe': {'includes': includes, 'include_files': include_files}},
executables=[Executable(main_python_file, base=base)])
I am creating key logger with python.
It works really good when I run script on PyCharm.
But when I compile them with py2exe, there are problem.
when keyboard hit, it creates other Qt dialog form.
Here is my sample code:
import pyHook, pythoncom
import time
import pyscreenshot as ps
import os
import sys
from PyQt4 import QtGui, QtCore
from PyQt4 import uic
class Form(QtGui.QDialog):
def __init__(self, parent=None):
log = open('log.txt', 'a')
log.write('INIT!!!!\n')
log.close()
QtGui.QDialog.__init__(self, parent)
self.ui = uic.loadUi("Keyhook_gui.ui")
self.ui.show()
self.isrun = True
self.pressed_set = {}
self.picture_set = {}
self.ui.start_button.clicked.connect(self.KeyLogStart)
self.ui.stop_button.clicked.connect(self.KeyLogStop)
def KeyLogStart(self):
hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = self.KeyDownEvent
hooks_manager.KeyUp = self.KeyUpEvent
hooks_manager.HookKeyboard()
while self.run():
pythoncom.PumpWaitingMessages()
def KeyLogStop(self):
log = open('log.txt', 'a')
log.write('KeyLogStop\n')
log.close()
self.isrun = False
def run(self):
return self.isrun
def KeyDownEvent(self, event):
log = open('log.txt', 'a')
log.write('KeyDownEvent in\n')
log.close()
try:
if event.Key in self.pressed_set:
log = open('log.txt', 'a')
log.write('PASS IN\n')
log.write(' event.Key = ' + str(event.Key) + '\n')
log.write('pressed_set = ' + str(self.pressed_set) + '\n')
log.close()
pass
else:
self.pressed_set[event.Key] = time.time()
self.picture_set[event.Key] = ps.grab()
log = open('log.txt', 'a')
log.write(str(event.Key) + ' Down\n')
log.close()
except Exception as e:
log = open('log.txt', 'a')
log.write(str(e) + 'a\n')
log.close()
log = open('log.txt', 'a')
log.write('pressed_set = ' + str(self.pressed_set)+'\n')
log.close()
return True
def KeyUpEvent(self, event):
log = open('log.txt', 'a')
log.write(str(event.Key) + ' Up\n')
log.write('pressed_set = ' + str(self.pressed_set) + '\n')
log.close()
pressed_time = time.time() - self.pressed_set.pop(event.Key)
self.picture_set[event.Key].save('img/' + event.Key + '_' + str(pressed_time) + '.jpg')
self.picture_set.pop(event.Key)
return True
def main():
app = QtGui.QApplication(sys.argv)
w = Form()
app.exec_()
if __name__ == '__main__':
if not os.path.isdir('./img'):
os.mkdir('./img')
main()
here is log file:
INIT!!!!
KeyDownEvent in
INIT!!!!
when keyboard hit, it goes to def__init__.
and creates other Qt dialog.
How can I fix this?