PyGTK The function takes exactly 1 argument (2 given) - python

I am trying to write a function to write text to a terminal window inside my application. But I am getting the above error.
Here's some of my code. This is GUI to play midi files. I am trying to display Opened file in my terminal window :
import pygtk
pygtk.require('2.0')
import gtk
import signal
import pango
import subprocess
textview = gtk.TextView()
class Teacher:
result = ""
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(400, 200)
window.set_title("The Improvisor")
window.connect("delete_event",
lambda w,e: gtk.main_quit())
table = gtk.Table(4, 4, True)
window.add(table)
button1 = gtk.Button("Open")
button1.connect("clicked", self.clicked_open_file)
button1.show()
button2 = gtk.Button("Play")
button2.connect("clicked", self.clicked_play)
button2.show()
button3 = gtk.Button("Stop")
button3.connect("clicked", self.clicked_stop)
button3.show()
fontdesc = pango.FontDescription('monospace')
textview.modify_font(fontdesc)
scroll = gtk.ScrolledWindow()
scroll.add(textview)
textview.show()
table.attach(button1, 0, 1, 0, 1)
table.attach(button2, 0, 1, 1, 2)
table.attach(button3, 0, 1, 2, 3)
table.attach(button4, 0, 4, 3, 4)
table.attach(scroll, 1, 4, 0, 3)
window.show_all()
def clicked_play(self, widget):
result = self.result
if result == "":
parent = None
alert = gtk.MessageDialog(parent, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO,
gtk.BUTTONS_CLOSE, "Please Select a File")
alert.run()
alert.destroy()
else :
self.proc = subprocess.Popen(["timidity", result])
def clicked_open_file(self, widget):
chooser = gtk.FileChooserDialog(title="Open a file",action=gtk.FILE_CHOOSER_ACTION_OPEN,
buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
response = chooser.run()
self.result = chooser.get_filename()
self.insert_text(self.result)
chooser.destroy()
def clicked_stop(self, widget=None):
if self.proc:
self.proc.terminate()
self.proc.wait()
def insert_text(text):
textview.get_buffer().insert_at_cursor(text)
def main(self):
signal.signal(signal.SIGTERM, self.clicked_stop)
gtk.main()
return 0
Teacher().main()

Your insert_text method lacks the self attribute. Change it to:
def insert_text(self, text):
...
Remember: the self argument in Python is the current instance of the class and must be declared explicitly as the first argument of a method.

Related

Retrieve data from a dialog in the calling window

I am struggling to retrieve results from a QDialog window and pass them back to the previous window. I want the user to be able to select a value/values, and then once they click okay in the dialog window, it should return them back to the previous window, and pass the text into the byVariables Textbox. The error returns on the line self.procUnivariate.byVariables.setText(item.text()). The error states:
AttributeError: 'ProcUnivariateVariables' object has no attribute 'procUnivariate'
I also tried using a return statement as you can see that is commented out. Unfortunately it seemed like the code got stuck and wasn't moving to the next line as I threw a print statement after and it never printed that line. I need help figuring out how to pass it back to the ProcUnivariate class once the okay button is clicked. Also, if I can figure this out, I'll likely turn the ProcUnivariate Class into a dialog window as well because it should take away the focus from the main window and shouldn't stay open if the main window is closed.
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QListWidget, QLineEdit, QTextEdit, QGridLayout, QHBoxLayout, QVBoxLayout, QDialog, QSizePolicy, QFileDialog, QTabWidget, QCheckBox
import PyQt5.QtGui as qtg
import glob
import os
from PyQt5.QtCore import Qt, QSettings
import inspect
from PyQt5 import QtCore
import pandas as pd
import pathlib
import pyreadstat
import json
class ProcUnivariateVariables(QDialog):
def __init__(self):
super().__init__()
self.procUnivariateByVariables = []
self.layout = QGridLayout()
self.setLayout(self.layout)
self.allVariables = QListWidget()
self.allVariables.setSelectionMode(3)
self.variablesSelected = QListWidget()
self.variablesSelected.setSelectionMode(3)
self.layout.addWidget(self.allVariables, 1,0, 4, 1)
self.layout.addWidget(self.variablesSelected, 1, 1, 4, 1)
self.okButton = QPushButton("Ok")
self.resetButton = QPushButton("Reset")
self.cancelButton = QPushButton("Cancel")
self.layout.addWidget(self.okButton, 1, 2)
self.layout.addWidget(self.resetButton, 2, 2)
self.layout.addWidget(self.cancelButton, 3, 2)
self.addByVariable = QPushButton(">")
self.removeVariable = QPushButton("<")
self.layout.addWidget(self.addByVariable, 5, 0)
self.layout.addWidget(self.removeVariable, 5, 1)
self.button_Connections()
def setItems(self, items):
self.allVariables.clear()
for item in items:
self.allVariables.addItem(item)
def add_by_variable(self):
selected_elements=[item.text() for item in self.allVariables.selectedItems()]
variableItem = self.variablesSelected.insertItems(self.variablesSelected.count(),selected_elements)
def button_Connections(self):
self.addByVariable.clicked.connect(self.add_by_variable)
self.removeVariable.clicked.connect(self.remove_variable)
self.okButton.clicked.connect(self.okay_clicked)
def remove_variable(self):
removeVariables = [item.text() for item in self.variablesSelected.selectedItems()]
self.selectedVariables.takeItems(removeVariables)
#sourceItem = self.currentSource.takeItem(oldSource)
def okay_clicked(self):
self.byVariablesSelected = [item.text() for item in self.variablesSelected.selectedItems()]
#self.procUnivariateByVariables = byVariablesSelected
print(self.byVariablesSelected)
self.accept()
#return self.byVariablesSelected
for item in self.byVariablesSelected:
print(item)
self.procUnivariate.byVariables.setText(item.text())
class ProcUnivariate(QWidget):
def __init__(self):
super().__init__()
self.procUnivariateVariables = None
layout = QGridLayout(self)
##Proc Univariate window Widgets
self.by = QLabel("By")
self.byVariables = QLineEdit()
self.byVariableList = QListWidget()
self.byButton = QPushButton("...")
self.varLabel = QLabel("Var")
self.classLabel = QLabel("Class")
self.freqLabel = QLabel("Freq")
self.histogramLabel = QLabel("Histogram")
self.freqBox = QLineEdit()
self.histBox = QLineEdit()
self.varBox = QLineEdit()
self.varButton = QPushButton("...")
self.sourceLabel = QLabel("Name")
self.sourceText = QLineEdit()
self.sourceButton = QPushButton("...")
self.selectionLabel = QLabel("Selection criteria")
self.selectionCriteria = QTextEdit()
self.statisticLabel = QLabel("Output")
self.statisticSearch = QLineEdit()
self.statisticList = QListWidget()
self.statisticList.setSortingEnabled(True)
self.outputLabel = QLabel("Output Statement")
self.outputText = QTextEdit()
self.fileOutputPath = QLineEdit("Output File Path")
self.runButton = QPushButton("Run")
self.previewButton = QPushButton("Preview")
self.okButton = QPushButton("Ok")
self.resetButton = QPushButton("Reset")
self.cancelButton = QPushButton("Cancel")
self.secondWindowConnections()
layout.addWidget(self.by, 1,0,1,1)
layout.addWidget(self.byVariables, 2, 0, 1, 4)
layout.addWidget(self.byButton, 2, 5, 1, 1)
#layout.addWidget(self.byVariableList, 3, 0, 1, 1)
layout.addWidget(self.freqLabel, 3, 0)
layout.addWidget(self.freqBox, 4, 0, 1, 4)
layout.addWidget(self.histogramLabel, 5, 0)
layout.addWidget(self.histBox, 6, 0, 1, 4)
layout.addWidget(self.varLabel, 7, 0, 1, 4)
layout.addWidget(self.varBox, 8, 0)
layout.addWidget(self.varButton, 8,5)
layout.addWidget(self.sourceLabel, 1, 6)
layout.addWidget(self.sourceText, 2, 6, 1, 4)
layout.addWidget(self.sourceButton, 2, 10)
layout.addWidget(self.selectionLabel, 3, 6)
layout.addWidget(self.selectionCriteria, 4, 6, 1, 4)
layout.addWidget(self.statisticLabel, 5, 6)
layout.addWidget(self.statisticSearch, 6, 6, 1, 4)
layout.addWidget(self.statisticList, 7, 6, 3, 4)
layout.addWidget(self.outputLabel, 10, 6)
layout.addWidget(self.outputText, 11, 6, 1, 4)
layout.addWidget(self.runButton, 12, 6)
layout.addWidget(self.previewButton, 12, 7)
layout.addWidget(self.okButton, 12, 8)
layout.addWidget(self.resetButton, 12, 9)
layout.addWidget(self.cancelButton, 12, 10)
self.setLayout(layout)
def secondWindowConnections(self): # this had a typo
self.byButton.clicked.connect(self.show_third_window)
def show_third_window(self):
if self.procUnivariateVariables is None: # if window has been created yet
self.procUnivariateVariables = ProcUnivariateVariables() # create window
if not self.procUnivariateVariables.isVisible(): # if window is showing
self.procUnivariateVariables.show() # show window
self.procUnivariateVariables.setItems(self.procUnivariateVariablesItems) # send items to window
def send_items(self, items): # this is to collect the variable that
self.procUnivariateVariablesItems = items # move to the third window
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Add a title
self.setWindowTitle("GUI Querying Program")
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.initUI()
self.setButtonConnections()
self.sw = None # dont initialize until neccessary.
def initUI(self):
subLayouts = {}
subLayouts['LeftColumn'] = QGridLayout()
self.layout.addLayout(subLayouts['LeftColumn'],1)
self.buttons = {}
self.buttons['addVariable'] = QPushButton('>')
self.buttons['removeVariable'] = QPushButton('<')
self.buttons['Toolkit'] = QPushButton('Toolkit')
self.variables = QListWidget()
self.selectedVariables = QListWidget()
subLayouts['LeftColumn'].addWidget(self.variables, 7,0,4,1)
subLayouts['LeftColumn'].addWidget(self.selectedVariables, 7,1,4,1)
subLayouts['LeftColumn'].addWidget(self.buttons['addVariable'], 10,0,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['removeVariable'], 10,1,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['Toolkit'], 11,1,1,1)
names = ['apple', 'banana', 'Cherry']
self.variables.insertItems(0, names)
def setButtonConnections(self):
self.buttons['addVariable'].clicked.connect(self.add_variable)
self.buttons['Toolkit'].clicked.connect(self.show_new_window)
# self.buttons['Toolkit'].clicked.connect(self.add_selected_variables)
# only use one connnect slot
def add_variable(self):
for item in self.variables.selectedItems():
self.selectedVariables.addItem(item.clone())
def show_new_window(self):
if self.sw is None: # check if window has been constructed
self.sw = ProcUnivariate() # construct window
if not self.sw.isVisible(): # If winow is not showing
self.sw.show() # show window
self.sw.send_items(self.add_selected_variables()) # send selected
# variables to second window
def add_selected_variables(self):
items = []
for i in range(self.selectedVariables.count()):
items.append(self.selectedVariables.item(i).clone())
# self.tw.setItems(items) ... self.tw doesnt exist so return them
return items
if __name__ == "__main__":
import sys
app = QApplication([])
mw = MainWindow()
mw.show()
app.exec()
What you need to do is connect a slot to the accepted signal of the dialog, and then retrieve the variables via a dedicated method of the dialog when that signal is emitted.
Here are all the relevant changes (fully tested as working):
class ProcUnivariateVariables(QDialog):
...
def button_Connections(self):
...
# connect to the dialog's built-in accept slot
self.okButton.clicked.connect(self.accept)
# add a method for retrieving the variables
def byVariablesSelected(self):
return [item.text() for item in self.variablesSelected.selectedItems()]
class ProcUnivariate(QWidget):
...
def secondWindowConnections(self): # this had a typo
self.byButton.clicked.connect(self.show_third_window)
self.varButton.clicked.connect(self.show_third_window)
def show_third_window(self):
if self.procUnivariateVariables is None: # if window has been created yet
self.procUnivariateVariables = ProcUnivariateVariables() # create window
# connect the new slot to the dialog's built-in accepted signal
self.procUnivariateVariables.accepted.connect(self.receive_selected_variables)
if not self.procUnivariateVariables.isVisible(): # if window is showing
self.procUnivariateVariables.show() # show window
self.procUnivariateVariables.setItems(self.procUnivariateVariablesItems) # send items to window
# set an identifier from the source button
self.procUnivariateVariables.sourceName = self.sender().text()
# add a slot for handling the dialog's accepted signal
def receive_selected_variables(self):
variables = self.procUnivariateVariables.byVariablesSelected()
text = ', '.join(variables)
if self.procUnivariateVariables.sourceName == 'byButton':
self.byVariables.setText(text)
else:
self.varBox.setText(text)
(Note that the above changes make the okay_clicked method of ProcUnivariateVariables redundant, so it should be removed).

How to store from a Gtk.Entry() as a variable, and then for example *10 and put the new value in a Gtk.Label() , in python3 using PyGObject?(PyGtk)

So I write the number in the entry and when I press the button, in label should appear my value multiplied by 10. But in return I have this error when I press the button: 'str' object has no attribute 'get_text'.
I don't know how to make it. Please help :(
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class EntryWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Entry Demo")
self.set_default_size(200, 100)
grid = Gtk.Grid()
self.add(grid)
self.entry1 = Gtk.Entry()
self.entry1.set_activates_default(True)
self.t1 = Gtk.Label()
button = Gtk.Button(label="CALC")
button.connect("clicked", self.calc)
grid.attach(self.entry1, 0, 1, 1, 1)
grid.attach(self.t1, 1,2,1,1)
grid.attach(button, 2,1,1,1)
def calc(self, widget, data=None):
port = self.entry1.get_text()
a = float(port.get_text())*10
self.t1.set_text(" " + a.get_text())
I have done it. I don't know if is it the best solutions, but this is it: (if someone have a better solution, I am all ears)
def init(self):
Gtk.Window.init(self, title="Change Label Text")
table = Gtk.Table(3, 3, True)
self.add(table)
adjustment = Gtk.Adjustment(0, 0, 100, 1, 10, 0)
self.spinbutton = Gtk.SpinButton()
self.spinbutton.set_adjustment(adjustment)
self.label = Gtk.Label("Press the button")
button = Gtk.Button("Press Me")
button.connect("clicked", self.button_pressed)
table.attach(self.label, 1, 2, 0, 1)
table.attach(button, 1, 2, 1, 2)
table.attach(self.spinbutton, 1, 2 ,2 ,3)
def button_pressed(self, button):
port = self.spinbutton.get_value()
self.label.set_text(str(int(port)*10))

Python GTK Window Marquee like behaviour

i am very new to python. I want to open a Python GTK Window which should display a moving text just like a marquee in HTML. Kindly anyone suggest a solution
i am using this piece of code:
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class MyProgram:
def __init__(self):
# create a new window
app_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
app_window.set_size_request(800, 350)
app_window.set_border_width(15)
app_window.set_title("Volks Electronics")
app_window.connect("delete_event", lambda w,e: gtk.main_quit())
vbox_app = gtk.VBox(False, 0)
app_window.add(vbox_app)
vbox_app.show()
label_app = gtk.Label("Sample Page ")
label_app.show()
vbox_app.pack_start(label_app, False, False, 1)
# Draw Table() to layout text:
table_layout = gtk.Table(rows=5, columns=5, homogeneous=True)
label_a = gtk.Label("Train Name:")
label_a.show()
table_layout.attach(label_a, 0, 1, 0, 1, 0,0,0,0)
label_c = gtk.Label("Train No:")
label_c.show()
table_layout.attach(label_c, 0, 1, 2, 3, 0,0,0,0)
label_d = gtk.Label("Departed From:")
label_d.show()
table_layout.attach(label_d, 0, 1, 3, 4, 0,0,0,0)
label_b = gtk.Label("Next Station:")
label_b.show()
table_layout.attach(label_b, 0, 1, 1, 2, 0,0,0,0)
table_layout.show()
vbox_app.add(table_layout)
# Use HBox() to layout text and button next to each other:
hbox_close = gtk.HBox(False, 0)
label_close = gtk.Label("Close aplication: ")
hbox_close.pack_start(label_close, True, True, 0)
label_close.show()
button_close = gtk.Button(stock=gtk.STOCK_CLOSE)
button_close.connect("clicked", lambda w: gtk.main_quit())
button_close.set_flags(gtk.CAN_DEFAULT)
hbox_close.pack_start(button_close, True, True, 0)
button_close.show()
hbox_close.show()
vbox_app.add(hbox_close)
# Place after association to hbox/vbox to avoid the following error:
# GtkWarning: gtkwidget.c:5460: widget not within a GtkWindow
button_close.grab_default()
app_window.show()
return
def main():
gtk.main()
return 0
if __name__ == "__main__":
MyProgram()
main()
I want to put some text after that close button which should work like a moving banner(marquee in HTML). I couldn't find any code which works like a marquee in a GTK window. Please suggest any way to do this
I like this.
#!/usr/bin/python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Hello World")
self.box = Gtk.Box(spacing=6)
self.add(self.box)
self.label = Gtk.Label()
self.box.pack_start(self.label, True, True, 0)
self.gibberish = "Spam and eggs, spam and eggs, spam and eggs!"
self.a = 0
self.z = 40
def marquee(self, text):
if self.a < len(text):
self.a = self.a + 1
self.z = self.z + 1
if self.a >= len(text):
self.a = 0
self.z = 40
return str(text[self.a:self.z])
# Displays Marquee
def displayMarquee(self):
# putting our text into our function and setting our label to the result.
# we need to return "True" to ensure the timer continues to run, otherwise it will only run once.
self.label.set_label(self.marquee(self.gibberish))
return True
# Initialize Marquee
def startMarquee(self):
# this takes 2 args: (how often to update in millisec, the method to run)
GObject.timeout_add(500, self.displayMarquee)
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
win.startMarquee()
Gtk.main()

How to disable the close button in GTK?

I have created a One Time Password mechanism in OpenERP 6.0.3's GTK client. After login the GTK client shows a window to enter the One Time Password as below.
Now I want to disable the close button at the top left of the window. How can I do that? I am using python and the code to create the window is:
EDIT
class sms_auth(gtk.Dialog):
def run_thread(self):
code=self.textbox_code.get_text()
self.result = rpc.session.rpc_exec_auth('/object', 'execute', 'res.users', 'check_code', code)
return self.result
def run(self):
self.show_all()
res = super(sms_auth, self).run()
result = None
if res == gtk.RESPONSE_ACCEPT:
result = self.run_thread()
self.destroy()
return result
def hide(*args):
window.hide()
return gtk.TRUE
def __init__(self, parent, response):
# To use cancel butto add gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.Dialog.__init__(
self, 'Sms Authentication', parent,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
)
label = gtk.Label("Please enter sms code :")
self.parent_widget = parent
self.response = False
self.db_login_response = response
self.connect('delete_event', hide)
self.textbox_code = gtk.Entry()
label.set_alignment(0,0)
table = gtk.Table(1, 7)
table.set_homogeneous(False)
table.set_col_spacings(40)
table.attach(label, 0, 6, 0, 1, ypadding=4)
table.attach(self.textbox_code, 5, 6, 0, 1, ypadding=4)
self.vbox.pack_start(table,False, False, 0)
Try like this
def hide(self, *args):
window.hide()
return gtk.TRUE
self.window.connect('delete_event', self.hide)
Note: Refer here
import pygtk
pygtk.require('2.0')
import gtk
class DialogExample(gtk.Dialog):
def __init__(self, parent=None):
gtk.Dialog.__init__(self, "My Dialog", parent,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
)
self.set_default_size(150, 100)
label = gtk.Label("This is a dialog to display additional information")
box = self.get_content_area()
box.add(label)
self.show_all()
self.connect('delete-event', self.delete_event)
def delete_event(self, widget, event=None):
print "Here"
return True
def main():
# rest in gtk_main and wait for the fun to begin!
gtk.main()
return 0
if __name__ == "__main__":
DialogExample()
main()

How to get background of textview in pygobject “gtk3”?

I'd like to get the current background color of my textview to change it and restore it later.
here what I tried:
context = textview.get_style_context()
state = Gtk.StateFlags.NORMAL
color = context.get_background_color(state)
I tried all possible states, but none returns the correct background color (white in my case)
Any idea how to get it?
I'm not exactly sure what you specific problem is without seeing more code, but here is a quick example that overrides the background and then restores it on a button click:
from gi.repository import Gtk, Gdk
import sys
class MyWindow(Gtk.ApplicationWindow):
def __init__(self, app):
Gtk.Window.__init__(self, title="Textview example", application=app)
self.set_default_size(250, 100)
self.set_border_width(10)
self.view = Gtk.TextView()
self.style_context = self.view.get_style_context()
self.default_bg_color = self.style_context.get_background_color(Gtk.StateFlags.NORMAL)
self.view.override_background_color(Gtk.StateFlags.NORMAL,
Gdk.RGBA(0, 0, 0, 1))
self.btn = Gtk.Button(label="Click Here")
self.btn.connect("clicked", self.on_btn_clicked)
box = Gtk.VBox()
box.pack_start(self.view, True, True, 0)
box.pack_start(self.btn, False, False, 0)
self.add(box)
def on_btn_clicked(self, widget):
current_bg = self.style_context.get_background_color(Gtk.StateFlags.NORMAL)
if current_bg == self.default_bg_color:
self.view.override_background_color(Gtk.StateFlags.NORMAL,
Gdk.RGBA(0, 0, 0, 1))
else:
self.view.override_background_color(Gtk.StateFlags.NORMAL,
self.default_bg_color)
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
win = MyWindow(self)
win.show_all()
def do_startup(self):
Gtk.Application.do_startup(self)
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)

Categories

Resources