Tkinter auto scrolling frame almost working. Apreciate input - scroll

I am trying to develop a scrollable frame in tkinter that can be used in the same way a normal frame can.
Thanks to many hint in this forum i develloped some code, that does exactly what it is supposed to, if i pack the scrollframe in the root window.
Unfortunately it fails if i use place or grid.
Here the code for the Frame
import tkinter as tk
class ScrollFrame(tk.Frame): #this frame will be placed on a canvas that is in a frame that goes on the parent window
class AutoScrollbar(tk.Scrollbar):
def set(self, *args):
if float(args[0])==0 and float(args[1])==1: self.grid_forget()
else:
if self.cget('orient')=="vertical": self.grid(row=0,column=1,sticky="ns")
else: self.grid(row=1,column=0,sticky="ew")
tk.Scrollbar.set(self, *args)
def __init__(self, root,*args,**args2):
self.outer_frame=tk.Frame(root,*args,**args2) #this is the frame that will be packed in th parent window
self.outer_frame.grid_columnconfigure(0, weight=1)
self.outer_frame.grid_rowconfigure(0, weight=2)
self.canvas = tk.Canvas(self.outer_frame, borderwidth=0, background="#ffffff")
tk.Frame.__init__(self, self.canvas,*args,**args2)
self.vscroll = ScrollFrame.AutoScrollbar(self.outer_frame, orient="vertical", command=self.canvas.yview)
self.hscroll = ScrollFrame.AutoScrollbar(self.outer_frame, orient="horizontal", command=self.canvas.xview)
self.canvas.configure(yscrollcommand=self.vscroll.set, xscrollcommand=self.hscroll.set)
self.canvas.create_window((0,0), window=self, anchor="nw")
self.canvas.grid(row=0,column=0,sticky="news")
self.hscroll.grid(row=1,column=0,sticky="ew")
self.vscroll.grid(row=0,column=1,sticky="ns")
self.bind("<Configure>", self.onFrameConfigure)
def onFrameConfigure(self, event): #Adapt the scroll region #does the resizing
self.canvas.config(scrollregion=self.canvas.bbox("all"))
self.canvas.config(width=event.width, height=event.height)
#convenience functions so the ScrollFrame can be treated like a normal frame
def destr_org(self):tk.Frame.destroy(self)
def destroy(self):
self.destroy=self.destr_org
self.outer_frame.destroy()
def pack(self,*args,**arg2):
self.outer_frame.pack(*args,**arg2)
def place(self,*args,**arg2):
self.outer_frame.place(*args,**arg2)
def grid(self,*args,**arg2):
self.outer_frame.grid(*args,**arg2)
def pack_forget(self,*args,**arg2):
self.outer_frame.pack_forget(*args,**arg2)
def place_forget(self,*args,**arg2):
self.outer_frame.place_forget(*args,**arg2)
def grid_forget(self,*args,**arg2):
self.outer_frame.grid_forget(*args,**arg2)
def config(self,*args,**arg2):
self.outer_frame.config(*args,**arg2)
tk.Frame.config(self,*args,**arg2)
def configure(self,*args,**arg2):
self.outer_frame.config(*args,**arg2)
tk.Frame.config(self,*args,**arg2)
here the code i used to test it. Just uncomment the f.place and f.grid lines to try them.
win=tk.Tk()
f=ScrollFrame(win)
for n in range(10):
o=tk.Button(f,text="-----------------------"+str(n)+"------------------------")
o.pack()
f.pack(expand=True, fill=tk.BOTH)
#f.place(x=0, y=0)
#f.grid(column=0,row=0)
Since i get no errors i am somewat lost and would be grateful for hints why it doesnt work.
I know there are packages with scrollable frames, but i really would like to get a frame without additional imports.
Its also tru that it is a little more complicated than necessary, but that is because I tried to design it in a way that it can be filled and placed exactly like a tk.Frame
Thanks a lot

Ok, I figured it out.
This works quite well for pack() and place() (didnt try to get grid working) (on Linux)
The key for place() is the binding to the resizing of the parent window, whereas for pack() the resizing of the inner frame (=self) seems to be important.
Even though the code of Novel (see comments above) is quite more elegant than mine, it sometimes gave me errors were this one worked :-)
class ScrollFrame(tk.Frame):
class AutoScrollbar(tk.Scrollbar):
def set(self, *args):
if float(args[0])==0 and float(args[1])==1: self.grid_forget()
else:
if self.cget('orient')=="vertical": self.grid(row=0,column=1,sticky="ns")
else: self.grid(row=1,column=0,sticky="ew")
tk.Scrollbar.set(self, *args)
def __init__(self, root,*args,**args2):
self.rootwin=root
self.dir=tk.BOTH
if "dir" in args2:
self.dir=args2["dir"]
del(args2["dir"])
self.outer_frame=tk.Frame(root,*args,**args2)
self.outer_frame.grid_columnconfigure(0, weight=1)
self.outer_frame.grid_rowconfigure(0, weight=2)
self.canvas = tk.Canvas(self.outer_frame, borderwidth=0, background="#ffffff")
tk.Frame.__init__(self, self.canvas,*args,**args2)
if self.dir==tk.Y or self.dir==tk.BOTH :
self.vscroll = ScrollFrame.AutoScrollbar(self.outer_frame, orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vscroll.set)
self.vscroll.grid(row=0,column=1,sticky="ns")
if self.dir==tk.X or self.dir==tk.BOTH :
self.hscroll = ScrollFrame.AutoScrollbar(self.outer_frame, orient="horizontal", command=self.canvas.xview)
self.canvas.configure(xscrollcommand=self.hscroll.set)
self.hscroll.grid(row=1,column=0,sticky="ew")
self.canvas.create_window((0,0), window=self, anchor="nw")
self.canvas.grid(row=0,column=0,sticky="news")
self.canvas.bind("<Enter>", self._bind_mouse)
self.canvas.bind("<Leave>", self._unbind_mouse)
def onFrameConfigure(self, event): #Adapt the scroll region
bb=self.canvas.bbox("all")
self.canvas.config(scrollregion=bb)
self.canvas.config(height=event.height,width=event.width)
def onRootConf(self, event):
bb=self.canvas.bbox("all")
self.canvas.config(scrollregion=bb)
w=bb[2]-bb[0]
h=bb[3]-bb[1]
rw=self.rootwin.winfo_width()-self.outer_frame.winfo_x()-20*int(self.vscroll.winfo_ismapped())
rh=self.rootwin.winfo_height()-self.outer_frame.winfo_y()-20*int(self.hscroll.winfo_ismapped())
if rh<h and (self.dir==tk.Y or self.dir==tk.BOTH):
h=rh
if rw<w and (self.dir==tk.X or self.dir==tk.BOTH):
w=rw
self.canvas.config(height=h,width=w)
def destr_org(self):tk.Frame.destroy(self)
def destroy(self):
self.destroy=self.destr_org
self.outer_frame.destroy()
def pack(self,*args,**arg2):
self.bind("<Configure>", self.onFrameConfigure)
self.outer_frame.pack(*args,**arg2)
def place(self,*args,**arg2):
self.outer_frame.place(*args,**arg2)
self.bind("<Configure>",self.onRootConf)
self.rootwin.bind("<Configure>",self.onRootConf)
def grid(self,*args,**arg2):
self.outer_frame.grid(*args,**arg2)
def pack_forget(self,*args,**arg2):
self.outer_frame.pack_forget(*args,**arg2)
def place_forget(self,*args,**arg2):
self.outer_frame.place_forget(*args,**arg2)
def grid_forget(self,*args,**arg2):
self.outer_frame.grid_forget(*args,**arg2)
def config(self,*args,**arg2):
self.outer_frame.config(*args,**arg2)
tk.Frame.config(self,*args,**arg2)
def configure(self,*args,**arg2):
self.outer_frame.config(*args,**arg2)
tk.Frame.config(self,*args,**arg2)
def winfo_ismapped(self):
return self.outer_frame.winfo_ismapped()
def _bind_mouse(self, event=None):
self.canvas.bind_all("<4>", self._on_mousewheel)
self.canvas.bind_all("<5>", self._on_mousewheel)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbind_mouse(self, event=None):
self.canvas.unbind_all("<4>")
self.canvas.unbind_all("<5>")
self.canvas.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
if event.num == 4 or event.delta == 120: self.canvas.yview_scroll(-1, "units" )
elif event.num == 5 or event.delta == -120: self.canvas.yview_scroll(1, "units" )

Related

Music and image failed to initialize

I was trying to make a multiple-choice music player using Gosu but the picture and music Iwanted would not initialize despite the program running, it showed a black screen. The single block of codes works:
require 'gosu'
require './input_functions'
class MW < Gosu::Window
def initialize
super 200, 135
#beth = Gosu::Image.new("media/beth.jpg")
#song = Gosu::Song.new("media/3rdmovement.mp3")
#song.play
end
def draw
#beth.draw(0, 0)
end
end
window = MW.new
window.show
But adding the multiple choice elements would not work(note: read_integer_in_range is defined in input function, the name itself is self explanatory). Full code:
require 'gosu'
require './input_functions'
class MW < Gosu::Window
def initialize
super 200, 135
#beth = Gosu::Image.new("media/beth.jpg")
#dimitri = Gosu::Image.new("media/dimitri.png")
#vil = Gosu::Image.new("media/vilva.png")
#song = Gosu::Song.new("media/3rdmovement.mp3")
#song2=Gosu::Song.new("media/2ndwaltz.mp3")
#song3=Gosu::Song.new("media/1stseason.mp3")
read_integer_in_range( "What song you want play
1st Spring
2nd Waltz
3rd movement", 1, 3)
choice = gets.chomp.to_i()
case choice
when 1
#song3.play
#vil.draw(0, 0)
when 2
#song2.play
#dimitri.draw(0, 0)
when 3
#song.play
draw_beth()
end
end
end
def draw_beth
#beth.draw(0, 0)
end
window = MW.new
window.show
All of the Png/Jpg and mp3 file works just fine..
I tried separating the draw_beth to call it in case but it did not work. I hope some passing by could help me with this one
As I can see, you are creating a music player with GUI, and if you are doing so, you shouldn't use gets function, instead you should track for the cursor's position and return a test value; for example:
def update
#locs = [mouse_x, mouse_y]
#cursor_choice_album = mouse_over_button(mouse_x, mouse_y)
end
def needs_cursor?; true; end
def mouse_over_button(mouse_x, mouse_y)
if ((mouse_x > 100 and mouse_x < 500) and (mouse_y < 500 and mouse_y > 100))
return 1
end
then you can use the case condition in the "button down ID" function

PyQt how to capture print output and display in text field

The following script is part of a more complex one. I have taken out some parts just for simplification.
My aim is to insert a textedit field that captures the print output of the command window (when the pushbutton is pressed) and displays it inside the text field while the program is executing.
The suggestions I found are too much aimed at scripts that have no other functions. But my script is already quite complex and I don’t want to change it from the beginning or rewrite the whole script.
Does anyone have an idea on how to include the function in the script in a relatively simple way? I have tried it without success.
Any kind help would be appreciated.
import sys
import subprocess
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.win_widget = WinWidget(self)
widget = QtGui.QWidget()
layout = QtGui.QVBoxLayout(widget)
layout.addWidget(self.win_widget)
self.setCentralWidget(widget)
self.statusBar().showMessage('Ready')
self.setGeometry(300, 300, 450, 250)
self.setWindowTitle('capture PyQt output')
self.setWindowIcon (QtGui.QIcon('logo.png'))
self.show()
class WinWidget (QtGui.QWidget) :
def __init__(self, parent):
super (WinWidget , self).__init__(parent)
self.controls()
self.grid_layout()
self.capture_output()
def controls(self):
self.btn_newSearch = QtGui.QPushButton('capture PyQt output', self)
self.btn_newSearch.clicked.connect(self.some_funtion)
self.btn_newSearch.setFont(QtGui.QFont('CourierNew', 12 , QtGui.QFont.Bold,False))
def capture_output (self) :
# HERE I WANT TO PUT A (IF POSSIBLE SIMPLE) SCRIPT TO CAPTURE
COOMAND WINDOW OUTPUT
something like:
self.text_box = QtGui.QPlainTextEdit()
text= capured output
self.text_box.setPlainText(text)
def grid_layout (self) :
grid = QtGui.QGridLayout()
grid.setSpacing(2)
grid.addWidget(self.btn_newSearch , 1 , 1)
grid.addWidget(self.text_box , 2 , 1)
self.setLayout(grid)
def some_funtion (self) :
print "hello world"
def main():
app = QtGui.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Arrow key event handling in PyObjC

I am trying to make an app using PyObjC and am struggling to find how to record arrow key (left and right). I would like to be able to record every time the user presses the left and right arrow keys. I am using another example found online. Instead of the buttons used in previous example for increment and detriment, I would like to use the arrow keys on the key board. Been looking a while and thought I could get some help here. Thanks!
from Cocoa import *
from Foundation import NSObject
class TAC_UI_Controller(NSWindowController):
counterTextField = objc.IBOutlet()
def windowDidLoad(self):
NSWindowController.windowDidLoad(self)
# Start the counter
self.count = 0
#objc.IBAction
def increment_(self, sender):
self.count += 1
self.updateDisplay()
#objc.IBAction
def decrement_(self, sender):
self.count -= 1
self.updateDisplay()
def updateDisplay(self):
self.counterTextField.setStringValue_(self.count)
if __name__ == "__main__":
app = NSApplication.sharedApplication()
# Initiate the contrller with a XIB
viewController = test.alloc().initWithWindowNibName_("test")
# Show the window
viewController.showWindow_(viewController)
# Bring app to top
NSApp.activateIgnoringOtherApps_(True)
from PyObjCTools import AppHelper
AppHelper.runEventLoop()
Your NSView-derived class should implement a keyDown_ and / or keyUp_. You also need to have acceptsFirstResponder return True:
from AppKit import NSView
class MyView(NSView)
def keyDown_(self, event):
pass
def keyUp_(self, event):
pass
def acceptsFirstResponder(self):
return True
Here'a an example implementation from the PyObjC documentation you can use: https://pythonhosted.org/pyobjc/examples/Cocoa/AppKit/DragItemAround/index.html

Can I make a QToolButton perform QLabel.setLayout(someLayout)? -- setting row height isn't working

My only GUI experience is with java.swing. I'm using PySide to update which of two QGridLayouts are set to a QLabel depending on a button press, but the actual update isn't happening. Making a call to self.update() after lines 123 and 130 didn't work. Should I be using a repaint event or something?
def displaySimulator(self):
if self.sim_vis == True: pass
else:
self.sim_vis = True
self.graph_vis = False
self.options.setLayout(self.simulator_settings)
def displayGraphing(self):
if self.graph_vis == True: pass
else:
self.graph_vis = True
self.sim_vis = False
self.options.setLayout(self.graphing_settings)
Here's the full code.
----------------------------------------------------------------------------------
Also, the toolbar label at the top is way too big...
self.layout.setRowMinimumHeight(0,20)
self.layout.setColumnMinimumWidth(0,250)
self.layout.setColumnMinimumWidth(1,1000)
setColumnMinimumWidth() works fine but setRowMinimumHeight() doesn't seem to work at all. I'm still a little confused about how the size of QWidgets are affected by layouts, containers, and subwidgets...perhaps I need to adjust the size of the QLabel, toolbar?
Try using a QWidget instead of a QLabel for self.options. Does that change anything?
For the toolbar spacing, do addStretch() after you add the last widget to the layout, but note that if you use a layout in a toolbar, you lose the built-in capabilities for it to autosize and hide buttons in a "... more options ..." type thing.
Since you name your object a toolbar I would actually make it a QToolbar. I would like to point out some styling points, because you said you were new.
import * is always bad for many reasons. You should know what you are importing and from where.
from PySide import QtGui, QtCore
Since you have a main GUI that you are running I would make that a QMainWindow. I would then add a menu bar and move some of your functionality to a file menu or edit menu.
This is just my style and how I like to do things
import sys
from PySide import QtGui, QtCore
class SimulatorWindow(QtGui.QMainWindow):
"""Application for running a simulator and displaying the resutls."""
def __init__(self):
super(SimulatorWindow, self).__init__()
self.setWindowTitle("Simulator") # Main window
# Properties
self.main_menu = None
self.simulator = None
self.export_action = None
self.settings_action = None
self.exit_action = None
self.initUI()
self.initMenu()
self.resize(600, 400)
# end Constructor
# Builds Simulator GUI
def initUI(self):
self.simulator = Simulator()
self.setCentralWidget(self.simulator)
self.addToolBar(self.simulator.toolbar)
# end initUI
def initMenu(self):
"""Initialize the menu bar."""
menubar = self.menuBar()
# ===== File Menu =====
self.file_menu = menubar.addMenu('&File')
# Export action
iexport = QtGui.QIcon()
self.export_action = QtGui.QAction(iexport, "Export", self)
self.export_action.triggered.connect(self.export)
self.file_menu.addAction(self.export_action)
# Separator
self.file_menu.addSeparator()
# Simulator Settings Dialog action
isettings = QtGui.QIcon()
self.settings_action = QtGui.QAction(isettings, "Settings", self)
self.settings_action.triggered.connect(self.simulator.dialog.show)
self.file_menu.addAction(self.settings_action)
# Exit action
iexit = QtGui.QIcon('exit.png')
self.exit_action = QtGui.QAction(iexit, '&Exit', self)
self.exit_action.triggered.connect(self.close)
self.file_menu.addAction(self.exit_action)
# ===== Edit Menu =====
self.edit_menu = menubar.addMenu('&Edit')
self.edit_menu.addAction(self.simulator.run_action)
# end initMenu
def export(self):
"""Export the simulation file."""
pass
# end export
# end class SimulatorWindow
class Simulator(QtGui.QWidget):
"""Simulator display."""
def __init__(self):
super().__init__()
#Properties
self.toolbar = None
self.dialog = None
self.run_action = None
# Layout
self.main_layout = QtGui.QGridLayout()
self.setLayout(self.main_layout)
# Graph
stuff = QtGui.QLabel("<font color=red size=300>Graphing stuff</font>")
stuff.setStyleSheet("QLabel {background-color: rgb(50,50,50); font-size:250;}")
stuff.setAlignment(QtCore.Qt.AlignCenter)
graph = QtGui.QLabel("<font color=green size=250>Graph here</font>")
graph.setStyleSheet("QLabel {background-color: rgb(0,0,0); font-size:250;}")
graph.setAlignment(QtCore.Qt.AlignCenter)
graph.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
self.main_layout.addWidget(stuff)
self.main_layout.addWidget(graph)
self.initToolbar()
self.initSettingsDialog()
# end Constructor
def initToolbar(self):
self.toolbar = QtGui.QToolBar()
irun = QtGui.QIcon()
self.run_action = QtGui.QAction(irun, "Run", self)
self.run_action.triggered.connect(self.run)
self.toolbar.addAction(self.run_action)
# end initToolbar
def initSettingsDialog(self):
"""Initialize the Settings dialog."""
self.dialog = QtGui.QDialog(self)
self.dialog.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowSystemMenuHint)
layout = QtGui.QGridLayout()
self.dialog.setLayout(layout)
# Initialize the Widgets
title = QtGui.QLabel("<font size=6>Simulator Settings</font>")
num_sim = QtGui.QLineEdit("Number of simulations")
num_trials = QtGui.QLineEdit("Number of trials (per learning phase)")
network = QtGui.QComboBox()
subject = QtGui.QComboBox()
# Set the layout
layout.addWidget(title, 0, 0, 1, 2, QtCore.Qt.AlignCenter)
layout.addWidget(num_sim, 1, 0)
layout.addWidget(num_trials, 1, 1)
layout.addWidget(network, 2, 0)
layout.addWidget(subject, 2, 1)
# end initSettingsDialog
def run(self):
"""Run the simulation."""
pass
# end run
# end class Simulator
def main():
"""Run the application."""
app = QtGui.QApplication(sys.argv)
window = SimulatorWindow()
window.show()
return app.exec_()
# end main
if __name__ == "__main__":
sys.exit(main())

Why keyPress Event in PyQt does not work for key Enter?

Why, when I press Enter, does the keyPressEvent method not do what I need? It just moves the cursor to a new line.
class TextArea(QTextEdit):
def __init__(self, parent):
super().__init__(parent=parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.show()
def SLOT_SendMsg(self):
return lambda: self.get_and_send()
def get_and_send(self):
text = self.toPlainText()
self.clear()
get_connect(text)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Enter:
self.get_and_send()
else:
super().keyPressEvent(event)
Qt.Key_Enter is the Enter located on the keypad:
Qt::Key_Return 0x01000004
Qt::Key_Enter 0x01000005 Typically located on the keypad.
Use:
def keyPressEvent(self, qKeyEvent):
print(qKeyEvent.key())
if qKeyEvent.key() == QtCore.Qt.Key_Return:
print('Enter pressed')
else:
super().keyPressEvent(qKeyEvent)
def keyPressEvent(self, event):
if (event.key() == 16777220) or (event.key() == 43): # for main keyboard and keypad
Works for my keyboard.
My grain of salt to complement the answers from #warvariuc and #tCot. A bit more pythonic:
def keyPressEvent(self, qKeyEvent):
if qKeyEvent.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
pass # your code
else:
super().keyPressEvent(qKeyEvent)

Resources