I've got a curses application that uses subwindows, but I can't seem to be able to delete them.
For example, this code doesn't work:
import curses
def fill(window, ch):
y, x = window.getmaxyx()
s = ch * (x - 1)
for line in range(y):
window.addstr(line, 0, s)
def main(stdscr):
fill(stdscr, 'M')
stdscr.refresh()
stdscr.getch()
subwin = stdscr.subwin(1, 28, 20, 13)
fill(subwin, 'J')
subwin.refresh()
subwin.getch()
del subwin
stdscr.touchwin()
stdscr.refresh()
stdscr.getch()
curses.wrapper(main)
When you run this code, the screen fills with 'M', then when you hit a key, a subwindow is created and filled with 'J'. Finally, when you press a key again, the code deletes the subwindow and completely redraws the screen. However, those Js are still there.
After some experimentation, I've found that calling the clear() method of stdscr will make the subwindow go, but I would like to restore the background as it was, without blanking it and rewriting.
Does anyone know a way in which this could be done?
Is there a good reason why you're using a subwindow? If you create a new top-level window then the code works correctly - simply change stdscr.subwin to curses.newwin and it works as you'd expect.
I'm not a curses expert, but I believe a subwindow shares the character buffer with its parent such that changes to either one will also affect the other. So, if you're looking to sub-divide a window into logical areas (perhaps a menu bar, main area and status bar) then subwindows are useful. If, however, you're looking for something more like a dialog box or pop-up menu then a whole new window (with its own separate buffer) is what you're after.
I can't find any definitive reference for ncurses which agrees or disagrees with me, but man page for AIX seems to corroborate it:
Recall that the subwindow shares its parent's window buffer. Changes made to the shared window buffer in the area covered by a subwindow, through either the parent window or any of its subwindows, affects all windows sharing the window buffer.
Of course, this isn't definitive for ncurses, but I can't find anything to the contrary and it certainly seems to explain the behaviour observed. I also did a crude experiment where, immediately after the subwin.getch() line in your example, I added this line:
raise Exception(stdscr.instr(20, 15, 3))
In your example, I get JJJ as the content of the actual main window. If I change to use curses.newwin() to create the window instead of stdscr.subwin() I get the expected MMM.
I don't know how many specific Python curses resources there are, but most of the standard tutorials and documents about ncurses are quite useful for this sort of level. Back when I had to do some work in it, this document was quite useful. If you scroll down to the "An Example" section, you'll see that the menu pop-ups are not subwindows - he alludes to this with the following slightly vague explanation:
We don't want this new window to overwrite previously written characters on the background. They should stay there after the menu closes. This is why the menu window can't be created as a subwindow of stdscr.
Also, I remember that using both stdscr and your own windows can cause issues - the "official" ncurses introduction has some warnings about this sort of thing. It also suggests avoiding overlapping windows entirely, as they're apparently error-prone, but I don't recall having any issues with them for short-term transient modal dialogs (which is the only use to which I put them). Of course, just because my simple use-case didn't expose any issues doesn't mean there aren't any. In something as complicated as ncurses, however, I can see the wisdom in keeping things as simple as you can.
I hope that's some help. As I said, I'm by no means a curses expert, but hopefully this gets you a few steps further along.
There are two problems with this code.
First, as the previous poster noted, subwindows share a buffer with the parent window, so you should use curses.newwin() if you want a completely independent window.
Second, using del to remove a window is problematic because it relies on reference counting/garbage collection to work properly. (For one thing, you have to delete all references to the window for it to work.) I recommend using the curses.panel module to explicitly show/hide the window.
Related
This question is about Veusz, a python-based plotting program. Not about usage, but about where to start hacking to fix a particular problem... This is on Windows.
Currently, when the program is launched it starts non-maximized, even if it was maximized last time it was closed. I can modify the shortcut to always start maximized but new windows opened within the app are always non-maximized.
Although it doesn't remember its maximized state, it does remember the size of last non-maximized window. As a workaround, I tried positioning the program top-left and resizing it as if it were maximized. However, when I open new windows from this one, they are offset from the top-left corner by the height of the "window bar". The offset does not cascade though; that is, opening a new window from an offset one results in a window in the same position.
I've been pawing through the program's files looking for somewhere window position might be saved or a default might be set. Not seeing anything, though. This is a Qt app so perhaps it's not Veusz-specific but I'm inclined to think it is. Spyder, for instance is Qt-based but I don't see this problem with it.
Does the community have any suggestions regarding changing this behavior? I don't understand the setup routine well enough yet. The source is on Github if you're feeling that helpful.
The relevant code is here in functions closeEvent (for saving state) and setupWindowGeometry (for loading state).
https://github.com/jeremysanders/veusz/blob/master/veusz/windows/mainwindow.py
Veusz needs to save the state of the window, as well as the geometry. Maybe doing something like this http://doc.qt.io/qt-4.8/restoring-geometry.html
I'm trying to use GTK3 and Cairo from Python for a minimal plotting application where the on-screen display of Cairo's output is for user convenience.
The typical usage is that I run a command, a plot pops up on screen and is also written to file, and I want to be able to dismiss the window as quickly as possible, ideally just a "q" keypress but also the common Ctrl-W and Ctrl-Q in addition to the default Alt-F4 (does anyone really use that regularly?!?).
I also want as little UI clutter in the window as possible: ideally just the standard window surround, no menus, toolbars, etc.
So... how can I bind my "q", "Ctrl-Q", etc. keybindings to Gtk.main_quit without having to a) create a cluttersome drop-down menu bar and b) go though the heavyweight Gtk.UIManager focused on by the Python Gtk+ 3 documentation here: http://python-gtk-3-tutorial.readthedocs.org/en/latest/menus.html . I hope this is possible, and doesn't require a lot of code (at least not as much as to set up all the menus!), but I can't find an example anywhere online: maybe I'm just searching for the wrong terms, being a GTK newbie.
Unfortunately there doesn't seem to be any documentation on making such a minimal accelerator setup, and the code to configure accelerator keys seems to differ a great deal between GTK2 and 3... thanks for helping.
Connect a signal to your main frame Win.connect('key-press-event', self.on_key_function) and in on_key_function (self, widget, event) check the value of event.keyval. For ESC is 65307 if you like hardcoded. Also, for key combinations, event.state report shift, alt(meta), and so on: if Gdk.ModifierType.CONTROL_MASK & event.state:do_something if ctrl is pressed
You could have separate stataments for left-ctrl, right-alt; be sure not to try to capture predefined key combinations, thay may be consumed by window manager.
A IDE with a good introspection will help you a lot, just write Gdk (previously imported) and autocompletion will popup a lot of functions/clases, most of them with a self-explanatory name.
Don't use key-press-event and keyval, it won't work for users with non-Latin keyboard layouts. GTK+ does a great job internally to match keyvals to hardware keys, this functionality is exposed via accelerators (often shortened as accel in the API) and bindings.
How to change the button decoration with wxPython, generally when the button is clicked, a dotted lines appear on the button.. any way to make that button not show the dotted lines?
Thanks
Assuming you're running your program on Windows (you didn't say which OS, but dotted lines are used by Windows Classic look), the dotted lines are called the focus rect, and they appear to mark a button or widget as focused. They are a system setting, and your program is acting as it should - wxWidgets is meant to emulate the underlying OS default behaviour as closely as possible.
Update
I don't think you can change this behaviour from inside the program. I really doubt that wxWidgets has a setting somewhere for this, as it is OS-dependent and is the standard and correct behaviour for the Classic theme. But the focus rect is shown by default only on the Classic Look which few people use.
Try switching to Luna theme (the default on XP), and you'll see that the focus rect won't appear unless you start hitting Tab while your window is in focus. By the way, the focus rect is needed exactly for when you are switching the focus using the Tab key. You need to see where the focus is, after all. That way you know when you press Enter or Space, which button is going to be pressed. Not everyone uses only the mouse.
You can use a custom button, for instance wx.lib.buttons.GenButton which is in pure python so you can overwrite the look, feel etc.
This also has a method SetUseFocusIndicator to turn off the dotted focus indicator
Is there any way I can create a UAC-like environment in Python? I want to basically lock the workstation without actually using the Windows lock screen. The user should not be able to do anything except, say, type a password to unlock the workstation.
You cannot do this without cooperation with operating system. Whatever you do, Ctrl-Alt-Del will allow the user to circumvent your lock.
The API call you're looking for Win32-wise is a combination of CreateDesktop and SetThreadDesktop.
In terms of the internals of Vista+ desktops, MSDN covers this, as does this blog post. This'll give you the requisite background to know what you're doing.
In terms of making it look like the UAC dialog - well, consent.exe actually takes a screenshot of the desktop and copies it to the background of the new desktop; otherwise, the desktop will be empty.
As the other answerer has pointed out - Ctrl+Alt+Delete will still work. There's no way around that - at least, not without replacing the keyboard driver, anyway.
As to how to do this in Python - it looks like pywin32 implements SetThreadDesktop etc. I'm not sure how compatible it is with Win32; if you find it doesn't work as you need, then you might need a python extension to do it. They're not nearly as hard to write as they sound.
You might be able to get the effect you desire using a GUI toolkit that draws a window that covers the entire screen, then do a global grab of the keyboard events. I'm not sure if it will catch something like ctrl-alt-del on windows, however.
For example, with Tkinter you can create a main window, then call the overrideredirect method to turn off all window decorations (the standard window titlebar and window borders, assuming your window manager has such things). You can query the size of the monitor, then set this window to that size. I'm not sure if this will let you overlay the OSX menubar, though. Finally, you can do a grab which will force all input to a specific window.
How effective this is depends on just how "locked out" you want the user to be. On a *nix/X11 system you can pretty much completely lock them out (so make sure you can remotely log in while testing, or you may have to forcibly reboot if your code has a bug). On windows or OSX the effectiveness might be a little less.
I would try with pygame, because it can lock mouse to itself and thus keep all input to itself, but i wouldn't call this secure without much testing, ctr-alt-del probably escape it, can't try on windows right now.
(not very different of Bryan Oakley's answer, except with pygame)
How to suppress end user ability to edit/add/delete text in a Text widget? (Python v3.2.. and tkinter)
The point is to suppress only the ability to change/add/delete text but not to castrate other features. Perhaps a NoEdit Text widged would be a better name.
I've tried .text['state'] = 'disabled' and it works almost OK in Windows (it still allows user to select/copy text highlights the selection, page up/down and up/down buttons work. The only thing broken seems to be the cursor made invisible.)
But on MacIntosh everything is broken. No highlights, no select/copy,... UGH
Since Tkinter has practically no documentation in Python, I've searched and found some TCL advise, to derive a new class and suppress the insert and delete functions.
So, I've tried as so:
class roText(tk.Text):
def insert(self,*args,**kwargs):
print(" Hey - Im inside roText.insert")
pass
def delete(self,*args,**twargs):
pass
def pInsert(self,*args,**twargs):
super().insert(*args,**twargs)
Unfortunately it didn't work right. Apparently tkinter does not use those insert and delete functions when end user enters/deletes code. Perhaps those TCL insert/delete are something else, and I lost something in translation from TCL and Swahili. What functions does tkinter.Text use for end user editing text? Hopefully they are not internal...
So, is there a way to modify the Text widget to suppress only end user editing?
Is there a way to do it without diving inside and overriding internal Tkinter code, so the stuff doesn't get broken by next releases of Tkinter?
Looking at the Idle shell window, I see that they've managed to suppress edits (except for the last line). So there is a way. But what is it and how costly?
Sorry for bumping an old question, but I was searching for an answer to this question also and finally found a solution. The solution I found involves overriding the key bindings when the text widget has focus and is pretty simple. Found here.
To override the bindings of a widget there is a bind function where you pass a string of what is to be overridden and the new function you want it to call.
self.txtBox.bind("<Key>", self.empty)
Somewhere else in the class you'll need to define the function to handle the event.
def empty(self, event):
return "break"
By returning the string "break" the event handler knows to stop after your function, instead of continuing with the default action.
I hope this answers your question. Cheers.
The reason the disabled state doesn't seem to work on the Mac is because it turns off the binding that gives focus to the widget. Without focus, the highlighting on a Mac doesn't show up. If you set the state to disabled but then assign a binding to <ButtonPress-1> to explicitly set focus to the disabled text widget, you can then select and copy text and the highlighting will show.
As for the cursor disappearing... arguably, that's what's supposed to happen. The cursor tells the user "this is where text will get inserted". Since no text will get inserted, having that visual clue would be confusing to the user. What you could do instead, if it was really important, is to insert a small image wherever they click to simulate the cursor.
To answer your question about whether the widget actually uses the insert and delete methods: the methods on the actual underlying widget are what the default bindings use, so overriding them in a subclass has no effect. You would need to redo all the default bindings for that to work. It's doable, but a lot of work.
Unfortunately, this is one area where programming in Tcl really shines, because you can simply disable the insert and delete commands of the widget. Of course, you can do that directly in Tkinter also since ultimately it runs tcl code to do everything, but that would involve writing some tcl code which is not a very good solution from the perspective of a Python coder.
I think the best solution is to use the disabled state, then add in just enough bindings to do what you want.
Here's a simple example that works by explicitly setting focus on a mouse button click. With this code I'm able to click and swipe to select a region, or double- or triple-click to select words and lines:
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.text = tk.Text(width=40, height=20)
self.text.bind("<1>", self.set_focus)
self.text.insert("end", "\n".join(dir(tk.Tk)))
self.text.configure(state="disabled")
self.text.pack(fill="both", expand=True)
def set_focus(self, event):
'''Explicitly set focus, so user can select and copy text'''
self.text.focus_set()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
#BryanOakley It took me a while to test your suggestion since I have no Mac.
Unfortunately Mac implementation of Python is buggy.
I've added focus, ie my disable function which I call after creating a window and inserting text, now calls first:
self.txt['state'] = 'disabled'
and then
self.txt.focus_set()
Which is what I think you've suggested.
It "kind of" worked. Ie: when selecting text (click and drag or double-click) highlighting works most of the time. Python must have some bad memory references or such bugs: Sometimes highlighting doesn't work at first, then it starts working (in the same window) after more clicking. Sometimes when program is invoked it works right of the bat. Sometimes selecting with Shift-rightArrow key will work but selecting with the mouse will not. Then starts working again. Or it will work fine in one window but not in another one (both of the same class), then starts working in all windows...etc...
The good thing is that adding focus did not affect badly Windows (ie all works fine as without focus.
I guess at this point I will just hope that future/next release of Python for Mac will fix those bugs..
BTW, it seems that Mac is a bit of an orphan for Python. Implementation is much uglier then for Windows. I mean the fonts look worse, the buttons, etc.. Or it could be due to different screen resolutions and Python ports that poorly account for those. Not sure
Anyway. Thank you for your help and suggestion to use focus for Mac.