Pre
I searched other Questions and couldn't find out the solution.
I want to execute Tab key and Shift operation simultaneously because I want to add a new performance by pressing tab key.I know the Shiftmodifier enum is good.
But it doesn't work when the key is Tab key.Do you know how to control it?
On the other hand,Controlmodifier works well.
When I pushed Tab key
tab only
When I pushed Tab & Control Key
tab & Control
When I pushed Any Key except for Tab & Shift Key
print("tab & any key except for tab key")
When I pushed Tab & Shift Key
No Response... Why?
Sample Code
from PySide import QtGui
from PySide import QtCore
import sys
class TSEditer(QtGui.QTextEdit):
def __init__(self,parent=None):
super(TSEditer,self).__init__(parent=None)
def keyPressEvent(self,event):
if event.key() == QtCore.Qt.Key_Tab and event.modifiers() == QtCore.Qt.ControlModifier:
print("tab & control")
elif event.key() == QtCore.Qt.Key_Tab and event.modifiers() == QtCore.Qt.ShiftModifier:
print("tab & shift")
elif event.key() == QtCore.Qt.Key_A and event.modifiers() == QtCore.Qt.ShiftModifier :
print("tab & any key except for tab key")
elif event.key() == QtCore.Qt.Key_Tab:
print("tab only")
return QtGui.QTextEdit.keyPressEvent(self,event)
def main():
try:
QtGui.QApplication([])
except Exception as e:
print(15,e)
ts = TSEditer()
ts.show()
sys.exit(QtGui.QApplication.exec_())
if __name__ == "__main__":
main()
Should be
if event.key() == QtCore.Qt.Key_Backtab:
i.e. Key_Backtab is combination of Tab and Shift
Related
I'm trying to trigger autocomplete to show itself after certain words are entered and finalized with a space which does work but only after double tapping space. It does momentarily show the autocomplete when you press space once but then disappears. Only after tapping space again does it show autocomplete and stays. Putting in print() statements to check if it's triggering on the first space does show it works fine but why it closes straight away, I don't know.
Current code:
class ScriptListener(sublime_plugin.EventListener):
commands = [
'&Command1',
'&Command2'
]
Command1_completions = [
'param1=',
'param2='
]
Command2_completions = [
'param1=',
'param2='
]
last_word = ""
current_row = ""
def on_query_completions(self, view, prefix, locations):
if not view.match_selector(locations[0], "source.script"):
return None
if self.last_word == self.commands[0] or self.commands[0] in self.current_row:
return self._remove_known_arguments(self.Command1_completions)
elif self.last_word == self.commands[1] or self.commands[1] in self.current_row:
return self._remove_known_arguments(self.Command2_completions)
else:
return None
def on_modified(self, view):
for region in view.sel():
if (' ' in view.substr(view.word(region))):
self.current_row = view.substr(view.line(view.sel()[0]))
if any(command in self.current_row for command in self.commands):
view.run_command("auto_complete")
else:
self.last_word = view.substr(view.word(region))
def on_selection_modified(self, view):
#Get current row
self.current_row = view.substr(view.line(view.sel()[0]))
def _remove_known_arguments(self, comp_list):
for arg in comp_list:
if (arg in self.current_row):
comp_list.remove(arg)
return comp_list
This program displays a home circuit breaker panel. the user can view what is on each breaker on the panel (data taken from an imported dictionary of entered breaker panel info) or the user can check what breakers control any list zone (kitchen basement, etc) The breakerville program closes when the user decides and is supposed to play a wave file at the close. It doesn't play after the program is made into an exe with pyinstaller just the windows 'beep'.
I am suspecting that I may need to edit the spec file to get the wave file to work after compiled. Is this correct and if so how? Do I need to modify the spec file?
from playsound import playsound # CURRENTLY USING
from chart import chart
from BreakerZones import BreakerZones
import time
import sys
import colorama
import yaml # to print the nested_lookup results(n) on separate lines
from nested_lookup import nested_lookup, get_all_keys # importing 2 items from nested_lookup
from colorama import Fore, Back, Style
colorama.init(autoreset=True) # If you don't want to print Style.RESET_ALL all the time,
# reset automatically after each print statement with True
print(colorama.ansi.clear_screen())
print('\n'*4) # prints a newline 4 times
print(Fore.MAGENTA + ' Arriving-' + Fore.GREEN + ' *** BREAKERVILLE USA ***')
def main():
print('\n' * 2)
print(Fore.BLUE + ' Breaker Numbers and Zones')
k = get_all_keys(BreakerZones)
# raw amount of keys even repeats , has quotes
new_l = [] # eliminate extra repeating nested keys
for e in k: # has quotes
if e not in new_l and sorted(e) not in new_l: #
new_l.append(e) #
print()
new_l.sort() # make alphabetical
newer_l = ('%s' % ', '.join(map(str, new_l)).strip("' ,")) # remove ['%s'] brackets so they don't show up when run
print(' ', yaml.dump(newer_l, default_flow_style=False)) # strip("' ,") or will see leading "' ," in output
print(Fore.BLUE + ' ENTER A BREAKER # OR ZONE', Fore.GREEN + ': ', end='')
i = input().strip().lower() # these lines is workaround for the colorama
print() # user input() issue of 'code' appearing in screen output
if i in k:
n = (nested_lookup(i, BreakerZones, wild=False, with_keys=False)) # wild=True means key not case sensitive,
print(yaml.dump(n, default_flow_style=False)) # 'with_keys' returns values + keys also
# for key, value in n.items(): eliminated by using yaml
# print(key, '--', value) eliminated by using yaml
else:
print(Fore.YELLOW + ' Typo,' + Fore.GREEN + ' try again')
main()
print()
print(Fore.GREEN + ' Continue? Y or N: C for breaker chart : ', end='') # see comments ENTER A BREAKER
ans = input().strip().lower() # strip() removes any spaces before or after user input
if ans == 'c':
chart()
print()
print(Fore.GREEN + ' Continue? Y or N : ', end='')
ans = input().strip().lower() # strip() removes any spaces before or after user input
if ans == 'y': # shorter version 'continue Y or N' after printing breaker chart
main()
else:
print()
print(Fore.MAGENTA + ' Departing -' + Fore.GREEN + ' *** BREAKERVILLE ***')
playsound('train whistle.wav')
time.sleep(2) # delay to exit program
sys.exit()
elif ans != 'y':
print()
print(Fore.MAGENTA + ' Good Day -' + Fore.GREEN + ' *** BREAKERVILLE ***')
playsound('train whistle.wav') #CURRENTLY USING
time.sleep(2) # delay to exit program
sys.exit()
else:
main()
main()
For the records: The issue is fixed by providing full path to the sound file.
This is probably linked to the implementation of playsound and how it determines what is the current working directory. Please refer to https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#run-time-information for a better understanding of that topic with pyinstaller
What I want to do is if I press the button on my mouse it uses a key like "E" and if I press the button again it uses the key "W" and after 2 seconds it resets, I mean if I don’t press the same button after 2 seconds it uses letter "e " again. Is that possible?
I've tried some codes but no results yet:
function OnEvent(event, arg, family)
if event == "MOUSE_BUTTON_PRESSED" and arg == 5 then
toggle = not toggle
if toggle then
PressKey("e")
ReleaseKey("e")
else
PressKey("w")
ReleaseKey("w")
end
end
end
local prev_tm_btn5 = -math.huge
function OnEvent(event, arg, family)
if event == "MOUSE_BUTTON_PRESSED" and arg == 5 then
local tm = GetRunningTime()
local key = tm - prev_tm_btn5 > 2000 and "e" or "w"
prev_tm_btn5 = tm
PressKey(key)
Sleep(15)
ReleaseKey(key)
end
end
I am a teacher that is writing a program to read an 8-digit ID barcode for students who are late to school. I am an experienced programmer, but new to Python and very new to Tkinter (about 36 hours experience) I have made heavy use of this site so far, but I have been unable to find the answer to this question:
How can I read exactly 8 digits, and display those 8 digits in a textbox immediately. I can do 7, but can't seem to get it to 8. Sometimes, I will get nothing in the text box. I have used Entry, bind , and everything works OK, except I can't seem to get the keys read in the bind event to place the keys in the textbox consistently that were inputted. The ID seems to be always correct when I PRINT it, but it is not correct in the textbox. I seem unable to be allowed to show the tkinter screen, so it shows only 7 digits or nothing in the text box upon completion.
Here is a snippet of my code, that deals with the GUI
from tkinter import *
from collections import Counter
import time
i=0
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.frame=Frame(width=400,height=400)
self.frame.pack()
self.frame.focus()
self.frame.bind('<Key>',self.key)
def key(self,event):
global i
self.frame.focus()
self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
if (i < 7):
i += 1
else:
#put my other python function calls here once I fix my problem
self.frame.after(2000)
#self.idScan.delete(0,END) #Then go blank for the next ID to be read
i=0
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()
enter image description here
You are doing some unusual things in order to place text inside the Entry field based on keypresses. I've changed your code so that it sets the focus on the Entry widget and will check the contents of the Entry field each time a key is pressed (while the Entry has focus). I'm then getting the contents of the Entry field and checking if the length is less than 8. If it is 8 (or greater) it will clear the box.
How does this work for you?
I've left in the commented out code
from tkinter import *
from collections import Counter
import time
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.idScan.focus_set()
self.frame=Frame(width=400,height=400)
self.frame.pack()
#self.frame.focus()
#self.frame.bind('<Key>',self.key)
self.idScan.bind('<Key>',self.key)
def key(self,event):
#self.frame.focus()
#self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
len(self.idScanned.get())
if (len(self.idScanned.get())<8):
pass
else:
#put my other python function calls here once I fix my problem
self.idScan.delete(0,END) #Then go blank for the next ID to be read
#self.frame.after(2000)
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()
I'm looking for a way for a user to edit data in bulk in a wxPython grid, a little like in Excel when you select a range, type data and press shift-Enter. This is a simplified version of my grid:
class MyGrid(gridlib.Grid):
def __init__(self, panel):
gridlib.Grid.__init__(self, panel)
self.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.onEditCell)
self.Bind(gridlib.EVT_GRID_RANGE_SELECT, self.onSelection)
def onSelection(self, event):
if self.GetSelectionBlockTopLeft() == []:
self.selected_row_number = 0
self.selected_col_number = 0
else:
self.selected_row_number = self.GetSelectionBlockBottomRight()[0][0] - self.GetSelectionBlockTopLeft()[0][0] + 1
self.selected_col_number = self.GetSelectionBlockBottomRight()[0][1] - self.GetSelectionBlockTopLeft()[0][1] + 1
print self.selected_row_number, self.selected_col_number
def onEditCell(self,event):
print self.selected_row_number, self.selected_col_number
The issue seems to be that the onEditCell event overwrites the previous selection. So I can select e.g. a four by four block in the grid, and onSelection will print 4 4. But when I start typing and press Enter, onEditCell will print 0,0 as if only the cell I'm editing was selected. How can I keep a "memory" of how many cells are selected? Thank you,
Answering my own question: I can get it to work with an ugly hack that doesn't seem like the right way to do things:
def onSelection(self, event):
self.previous_selected_row_number = self.selected_row_number
self.previous_selected_col_number = self.selected_col_number
if self.GetSelectionBlockTopLeft() == []:
self.selected_row_number = 0
self.selected_col_number = 0
else:
self.selected_row_number = self.GetSelectionBlockBottomRight()[0][0] - self.GetSelectionBlockTopLeft()[0][0] + 1
self.selected_col_number = self.GetSelectionBlockBottomRight()[0][1] - self.GetSelectionBlockTopLeft()[0][1] + 1
print self.selected_row_number, self.selected_col_number
print self.previous_selected_row_number, self.previous_selected_col_number
def onEditCell(self,event):
print self.previous_selected_row_number, self.previous_selected_col_number
If anyone can think of a better way...