Welcome Guest ( Log In | Register )

3 Pages  1 2 3 >Bottom

Outline · [ Standard ] · Linear+

 Read .txt file in Glade GUI, python + glade

views
     
TSLaw
post Mar 23 2009, 03:01 AM, updated 17y ago

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
I'm currently doing a simple application by using python + glade...

Can anyone roughly tell me how to read my .txt file on textview? i tried google-ing, i should use buffer() function to read right?

I was doing this for few days, but still cant get the .txt file appear on my GUI application...

Can someone help me up ??

Thanks...
oshiri
post Mar 23 2009, 12:40 PM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
This is an example which I often use:

CODE
def mytxt(self):
 textview1 = self.wTree.get_widget("textview1")
 file = open('xxxx.txt')
 string = file.read()
 buffer = textview1.get_buffer()
 buffer.set_text(string)
 textview1.scroll_mark_onscreen(buffer.get_insert())
 file.close()
 return True

TSLaw
post Mar 24 2009, 05:24 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
bro oshiri,

I stil cant get the text file on my GUI screen...

Do you mind to have a look on my code...

Thanks & appreciate your help...


My idea is when the "searching button" is clicked...then the text will automatically show up on the textview, but it seems like i failed to do it...

This post has been edited by Law: Mar 24 2009, 05:28 PM


Attached File(s)
Attached File  folder.tar.gz ( 2.37k ) Number of downloads: 38
oshiri
post Mar 24 2009, 07:59 PM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
I remove your second window in glade file.
I also change button2 signal from button2_activated to button2_clicked.

Edited glade file:

CODE
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
[bad html removed]*- mode: xml -*-->
<glade-interface>
 <widget class="GtkWindow" id="window1">
   <property name="visible">True</property>
   <property name="title" translatable="yes">window1</property>
   <signal name="destroy" handler="on_window1_destroy"/>
   <child>
     <widget class="GtkVBox" id="vbox1">
       <property name="visible">True</property>
       <child>
         <widget class="GtkLabel" id="label1">
           <property name="visible">True</property>
           <property name="label" translatable="yes">Please press the Searching button to view the content:
</property>
         </widget>
         <packing>
           <property name="expand">False</property>
           <property name="fill">False</property>
         </packing>
       </child>
       <child>
         <widget class="GtkScrolledWindow" id="scrolledwindow1">
           <property name="visible">True</property>
           <property name="can_focus">True</property>
           <child>
             <widget class="GtkTextView" id="textview1">
               <property name="width_request">26</property>
               <property name="height_request">17</property>
               <property name="visible">True</property>
               <property name="can_focus">True</property>
               <property name="cursor_visible">False</property>
               <property name="overwrite">True</property>
               <signal name="show" handler="on_textview_show"/>
             </widget>
           </child>
         </widget>
         <packing>
           <property name="padding">10</property>
           <property name="position">1</property>
         </packing>
       </child>
       <child>
         <widget class="GtkHSeparator" id="hseparator1">
           <property name="visible">True</property>
         </widget>
         <packing>
           <property name="position">2</property>
         </packing>
       </child>
       <child>
         <widget class="GtkHBox" id="hbox1">
           <property name="visible">True</property>
           <child>
             <widget class="GtkLabel" id="label2">
               <property name="visible">True</property>
               <property name="label" translatable="yes">Please copy the content to text entry below:</property>
             </widget>
             <packing>
               <property name="expand">False</property>
               <property name="fill">False</property>
             </packing>
           </child>
         </widget>
         <packing>
           <property name="position">3</property>
         </packing>
       </child>
       <child>
         <widget class="GtkEntry" id="entry1">
           <property name="visible">True</property>
           <property name="can_focus">True</property>
           <property name="invisible_char">*</property>
           <signal name="insert_text" handler="on_entry1_insert_text"/>
         </widget>
         <packing>
           <property name="expand">False</property>
           <property name="fill">False</property>
           <property name="position">4</property>
         </packing>
       </child>
       <child>
         <widget class="GtkHButtonBox" id="hbuttonbox1">
           <property name="visible">True</property>
           <child>
             <widget class="GtkButton" id="button1">
               <property name="visible">True</property>
               <property name="can_focus">True</property>
               <property name="can_default">True</property>
               <property name="label">gtk-ok</property>
               <property name="use_stock">True</property>
               <property name="response_id">0</property>
             </widget>
           </child>
           <child>
             <widget class="GtkButton" id="button2">
               <property name="visible">True</property>
               <property name="can_focus">True</property>
               <property name="can_default">True</property>
               <property name="response_id">0</property>
               <signal name="clicked" handler="on_button2_clicked"/>
               <child>
                 <widget class="GtkAlignment" id="alignment1">
                   <property name="visible">True</property>
                   <property name="xscale">0</property>
                   <property name="yscale">0</property>
                   <child>
                     <widget class="GtkHBox" id="hbox2">
                       <property name="visible">True</property>
                       <property name="spacing">2</property>
                       <child>
                         <widget class="GtkImage" id="image1">
                           <property name="visible">True</property>
                           <property name="stock">gtk-find</property>
                         </widget>
                         <packing>
                           <property name="expand">False</property>
                           <property name="fill">False</property>
                         </packing>
                       </child>
                       <child>
                         <widget class="GtkLabel" id="label3">
                           <property name="visible">True</property>
                           <property name="label" translatable="yes">Searching</property>
                           <property name="use_underline">True</property>
                         </widget>
                         <packing>
                           <property name="expand">False</property>
                           <property name="fill">False</property>
                           <property name="position">1</property>
                         </packing>
                       </child>
                     </widget>
                   </child>
                 </widget>
               </child>
             </widget>
             <packing>
               <property name="position">1</property>
             </packing>
           </child>
         </widget>
         <packing>
           <property name="position">5</property>
         </packing>
       </child>
     </widget>
   </child>
 </widget>
</glade-interface>


For the python file, I edited and include button2 (Searching), so when you clicked button Searching it will show content of the text file.
And edited file for python file:

CODE
#!/usr/bin/env python
import os, os.path
import sys

try:
 import pygtk
  pygtk.require("2.0")
except:
  pass
try:
import gtk
  import gtk.glade
except:
sys.exit(1)

class result:

def __init__(self):

 self.gladefile = "project6.glade"
 self.wTree = gtk.glade.XML(self.gladefile)
 

 dic = { "on_button2_clicked" : self.on_button2_clicked,
 "on_window1_destroy" : gtk.main_quit}

 self.wTree.signal_autoconnect(dic)


def on_button2_clicked(self, widget):
 textview1 = self.wTree.get_widget("textview1")
 file = open('super.txt')
 string = file.read()
 buffer = textview1.get_buffer()
 buffer.set_text(string)
 textview1.scroll_mark_onscreen(buffer.get_insert())
 file.close()
 return True
 
 
 
 


if __name__ == "__main__":
gui = result()
gtk.main()



The output:
user posted image

TSLaw
post Mar 25 2009, 03:41 AM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
Oh yes, i did it...you are cool man...
you saved me...

It is not that hard as i thought


Added on March 25, 2009, 3:50 amHi Oshiri

I'm moving to my next step for my GUI now...

How can i execute a command on terminal through my GUI (when a button is clicked)...??

Should i connect the "button" signal to "run" in order to execute the commands line on my terminal?

Do you have any website link so that i can learn from there?
python + glade are very interesting

This post has been edited by Law: Mar 25 2009, 03:50 AM
oshiri
post Mar 25 2009, 10:08 AM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
QUOTE(Law @ Mar 25 2009, 03:41 AM)
Oh yes, i did it...you are cool man...
you saved me...

It is not that hard as i thought


Added on March 25, 2009, 3:50 amHi Oshiri

I'm moving to my next step for my GUI now...

How can i execute a command on terminal through my GUI (when a button is clicked)...??

Should i connect the "button" signal to "run" in order to execute the commands line on my terminal?

Do you have any website link so that i can learn from there?
python + glade are very interesting
*
Better use signal clicked because you want to click button to do something.

There are several ways you can run thirdparty command fron python.

1. import os
os.system("command")
2. import os
stream = os.popen("command")
3. import subprocess
print os.popen("command").read()
4. import subprocess
print Popen("command", stdout=PIPE, shell=True).stdout.read()
5. import subprocess
return_code = call("command", shell=True)

http://www.python.org/doc/2.5/lib/module-subprocess.html
http://www.learningpython.com/2006/05/30/b...ygtk-and-glade/


TSLaw
post Mar 25 2009, 12:22 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
Thanks for your reply

I need some time to read through them, i will try by myself first...

If anything i cant solve or understand, hope you can advise me here...

Thanks again...


Added on March 26, 2009, 5:41 pmHi oshiri,

For example:

i would like to run this command on terminal through my GUI:

CODE


hcitool scan hci0



This is bluetooth scanning command.

I would like to scan the bluetooth devices when a <<button>> is clicked on my GUI...
After the scanning process is finished, the available bluetooth devices will be shown on my textview...

Can i do this with python...??

Thanks again and looking forward your advises...


Added on March 26, 2009, 8:19 pmi get this pygtk example...

Im trying to done this with glade instead of pygtk...

here is the code:

CODE
#!/usr/bin/env python
"""Show a shell command's output in a gtk.TextView without freezing the UI"""

import os, threading, locale

import gobject
import gtk

gobject.threads_init()
gtk.gdk.threads_init()

encoding = locale.getpreferredencoding()
utf8conv = lambda x : unicode(x, encoding).encode('utf8')

def on_button_clicked(button, view, buffer, command):
    thr = threading.Thread(target= read_output, args=(view, buffer, command))
    thr.start()

def read_output(view, buffer, command):
    stdin, stdouterr = os.popen4(command)
    while 1:
        line = stdouterr.readline()
        if not line:
            break
        gtk.gdk.threads_enter()
        iter = buffer.get_end_iter()
        buffer.place_cursor(iter)
        buffer.insert(iter, utf8conv(line))
        view.scroll_to_mark(buffer.get_insert(), 0.1)
        gtk.gdk.threads_leave()

sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
textview = gtk.TextView()
textbuffer = textview.get_buffer()
sw.add(textview)
win = gtk.Window()
win.resize(300,500)
win.connect('delete-event', gtk.main_quit)
button = gtk.Button(u"Press me!")
command = 'ls -R %s' % (os.getcwd(),)
button.connect("clicked", on_button_clicked, textview, textbuffer, command)
vbox = gtk.VBox()
vbox.pack_start(button, False)
vbox.pack_start(sw)
win.add(vbox)
win.show_all()

gtk.main()


I got this error: AttributeError: result instance has no attribute 'textbuffer' with a modified code from above...

This post has been edited by Law: Mar 26 2009, 08:19 PM
TSLaw
post Mar 27 2009, 12:02 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
CODE
#!/usr/bin/env python
import os, os.path, threading, locale
import sys
try:
 import pygtk
  pygtk.require("2.0")
except:
  pass
try:
import gtk
  import gtk.glade
import gobject
except:
sys.exit(1)

encoding = locale.getpreferredencoding()
utf8conv = lambda x : unicode(x, encoding).encode('utf8')


class result:

def __init__(self):

 self.gladefile = "project6.glade"
 self.wTree = gtk.glade.XML(self.gladefile)
 

 dic = { "on_window1_destroy" : gtk.main_quit,
  "on_button1_clicked" : self.on_scan
         }

 self.wTree.signal_autoconnect(dic)

 
def on_scan(self, obj):
 thr = threading.Thread(target= self.read_output, args=(self.textbuffer, self.command))
 thr.run()

 self.command = "hcitool scan"
 textview1 = self.wTree.get_widget("textview1")
 self.textbuffer = textview1.get_buffer()
 textview1.scroll_mark_onscreen(buffer.get_insert())  
 

def read_output(self, buffer, command):
 stdin, stdouterr = os.popen4(command)
 for line in stdouterr.readlines():
   buffer.insert(buffer.get_end_iter(), utf8conv(line))




 


if __name__ == "__main__":
rst = result()

gtk.main()
 
 





Is there any wrong on this code??
oshiri
post Mar 27 2009, 07:17 PM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
I'm also having problem with sending output from command line to textview.
I don't know if it is possible.
The trick I always do is pass the output to a temporary file and read it to textview.

Example, same code as i gave you (this is for viewing "ps ax" output):

CODE
class result:

       def __init__(self):

               self.gladefile = "project6.glade"
               self.wTree = gtk.glade.XML(self.gladefile)


               dic = { "on_button2_clicked" : self.on_button2_clicked,
               "on_window1_destroy" : gtk.main_quit}

               self.wTree.signal_autoconnect(dic)

       def on_button2_clicked(self, widget):
               textview1 = self.wTree.get_widget("textview1")
               os.system('ps ax > output')
               file = open('output')
               string = file.read()
               buffer = textview1.get_buffer()
               buffer.set_text(string)
               textview1.scroll_mark_onscreen(buffer.get_insert())
               file.close()
               os.system('rm -f output')
               return True


This post has been edited by oshiri: Mar 27 2009, 07:20 PM
TSLaw
post Mar 27 2009, 10:50 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
Yeah...

This question is driving me crazy...

Let's do it together and share our knowledge together here...

I really like python...
oshiri
post Mar 30 2009, 11:38 AM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
Good news.... finaly I got it working without using temporary file.

The code:

CODE
       def on_button2_clicked(self, buffer):
               stdin, stdouterr = os.popen4('ps ax')
               for line in stdouterr.readlines():
                       textview1 = self.wTree.get_widget("textview1")
                       buffer = textview1.get_buffer()
                       buffer.insert(buffer.get_end_iter(), utf8conv(line))

TSLaw
post Mar 31 2009, 05:20 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
All right man !!!

You are surprising me...

Your codes is more simplified easier...

Do you have any idea about this command <<< utf8conv(line) >>>>


oshiri
post Apr 1 2009, 09:00 AM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
QUOTE(Law @ Mar 31 2009, 05:20 PM)
All right man !!!

You are surprising me...

Your codes is more simplified easier...

Do you have any  idea about this command <<< utf8conv(line) >>>>
*
That will convert character to utf8. Came from this:
encoding = locale.getlocale()[1]
utf8conv = lambda x : unicode(x, encoding).encode('utf8')

TSLaw
post Apr 1 2009, 04:27 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
The next thing I would like to learn will be radio button...

Seems like not much tutorial about radio button can be found online...


Added on April 1, 2009, 6:47 pm
CODE


self.window1 = gtk.glade.XML ("project5.glade")
 self.window2 = self.window1.get_widget("window2")

 dic = { "on_window1_destroy" : gtk.main_quit,
  "on_radiobutton1_toggled" : self.on_rd1,
  "on_radiobutton2_toggled" : self.on_rd2,
  "on_radiobutton3_toggled" : self.on_rd3,
  "on_button1_clicked" : self.window2_show
 
  }

 self.window1.signal_autoconnect(dic)
 window1 = self.window1.get_widget("window1")

def on_rd1(self, widget):
                      if self.on_rd1.get_active():
                      self.on_rd1 = "window2"
               else:
                      self.on_rd2 = "window3"
                      self.on_rd3 = "window4"
 

def window2_show(self, widget):
              self.window2_show
              return True



I want to make one of the radio button get activated and proceed to next window when <<OK>> is clicked, the code will be something as above right?

I think i missed up something...



This post has been edited by Law: Apr 1 2009, 06:47 PM
TSLaw
post Apr 6 2009, 06:14 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
Anyone??

Help me out please...
oshiri
post Apr 7 2009, 11:56 AM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
Next time please don't add in previous post.
Post on a new thread so that your post will be on top and people will know it.

Okay... for anybody wants to learn pygtk and glade, I would like to suggest Tepache.
http://kefir.sourceforge.net/tepache/index.html

Debian user can just: apt-get install tepache

This application will create a basic python code from your glade file.


This is my example code using tepache for radiobutton.
This example will open different window when you choose different radionbutton and click OK button:

CODE
#!/usr/bin/env python
# -*- coding: UTF8 -*-

# Python module project2.py
# Autogenerated from project2.glade
# Generated on Tue Apr  7 11:22:14 2009

# Warning: Do not modify any context comment such as #--
# They are required to keep user's code

import os

import gtk

from SimpleGladeApp import SimpleGladeApp
from SimpleGladeApp import bindtextdomain

app_name = "project2"
app_version = "0.0.1"

glade_dir = ""
locale_dir = ""

bindtextdomain(app_name, locale_dir)


class Window1(SimpleGladeApp):

   def __init__(self, path="project2.glade",
                root="window1",
                domain=app_name, **kwargs):
       path = os.path.join(glade_dir, path)
       SimpleGladeApp.__init__(self, path, root, domain, **kwargs)
   

   #-- Window1.new {
   def new(self):
       print "A new %s has been created" % self.__class__.__name__
   #-- Window1.new }

   #-- Window1 custom methods {
   #   Write your own methods here
   #-- Window1 custom methods }

   #-- Window1.on_window1_destroy {
   def on_window1_destroy(self, widget, *args):
       print "on_window1_destroy called with self.%s" % widget.get_name()
       gtk.main_quit()
   #-- Window1.on_window1_destroy }

   def on_window2_destroy(self, widget, *args):
       print "on_window1_destroy called with self.%s" % widget.get_name()
       gtk.main_quit()
   #-- Window2.on_window2_destroy }
   
   def on_window3_destroy(self, widget, *args):
       print "on_window1_destroy called with self.%s" % widget.get_name()
       gtk.main_quit()
   #-- Window3.on_window3_destroy }
   
   def on_window4_destroy(self, widget, *args):
       print "on_window1_destroy called with self.%s" % widget.get_name()
       gtk.main_quit()
   #-- Window4.on_window4_destroy }
   
   #-- Window1.on_button2_clicked {   def on_button2_clicked(self, widget, *args):
   def on_button2_clicked(self, widget, *args):
       print "on_button2_clicked called with self.%s" % widget.get_name()
       gtk.main_quit()
   #-- Window1.on_button2_clicked }

   #-- Window1.on_button1_clicked {
   def on_button1_clicked(self, widget, *args):
       print "on_button1_clicked called with self.%s" % widget.get_name()
       if self.radiobutton1.get_active():
           Window2()
       if self.radiobutton2.get_active():
           Window3()
       if self.radiobutton3.get_active():
           Window4()
    #-- Window1.on_button1_clicked }

   #-- Window1.on_radiobutton1_toggled {
   def on_radiobutton1_toggled(self, widget, *args):
       print "on_radiobutton1_toggled called with self.%s" % widget.get_name()
   #-- Window1.on_radiobutton1_toggled }

   #-- Window1.on_radiobutton2_toggled {
   def on_radiobutton2_toggled(self, widget, *args):
       print "on_radiobutton2_toggled called with self.%s" % widget.get_name()
   #-- Window1.on_radiobutton2_toggled }
   
   #-- Window1.on_radiobutton3_toggled {
   def on_radiobutton3_toggled(self, widget, *args):
       print "on_radiobutton3_toggled called with self.%s" % widget.get_name()
   #-- Window1.on_radiobutton3_toggled }


class Window2(SimpleGladeApp):

   def __init__(self, path="project2.glade",
                root="window2",
                domain=app_name, **kwargs):
       path = os.path.join(glade_dir, path)
       SimpleGladeApp.__init__(self, path, root, domain, **kwargs)

   #-- Window2.new {
   def new(self):
       print "A new %s has been created" % self.__class__.__name__
   #-- Window2.new }

   #-- Window2 custom methods {
   #   Write your own methods here
   #-- Window2 custom methods }


class Window3(SimpleGladeApp):

   def __init__(self, path="project2.glade",
                root="window3",
                domain=app_name, **kwargs):
       path = os.path.join(glade_dir, path)
       SimpleGladeApp.__init__(self, path, root, domain, **kwargs)

   #-- Window3.new {
   def new(self):
       print "A new %s has been created" % self.__class__.__name__
   #-- Window3.new }

   #-- Window3 custom methods {
   #   Write your own methods here
   #-- Window3 custom methods }


class Window4(SimpleGladeApp):

   def __init__(self, path="project2.glade",
                root="window4",
                domain=app_name, **kwargs):
       path = os.path.join(glade_dir, path)
       SimpleGladeApp.__init__(self, path, root, domain, **kwargs)

   #-- Window4.new {
   def new(self):
       print "A new %s has been created" % self.__class__.__name__
   #-- Window4.new }

   #-- Window4 custom methods {
   #   Write your own methods here
   #-- Window4 custom methods }


#-- main {

def main():
   window1 = Window1()
   #window2 = Window2()
   #window3 = Window3()
   #window4 = Window4()

   window1.run()

if __name__ == "__main__":
   main()

#-- main }



Screenshot:

user posted image

This post has been edited by oshiri: Apr 10 2009, 01:36 PM
TSLaw
post Apr 10 2009, 11:47 AM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
Tepache only support for lenny version for debian..

btw im using etch version...
oshiri
post Apr 10 2009, 01:30 PM

Enthusiast
*****
Senior Member
751 posts

Joined: Nov 2004
You can compile it yourself.
It only requires python 2.3 and above development package and python-support

if you are using python2.5:
apt-get install python2.5-dev python-support
then compile.

This is another trick for debian user, sometimes work, sometimes don't..
Get tepache package from debian lenny:
wget http://http.us.debian.org/debian/pool/main...e_1.1-5_all.deb

Extract package:
dpkg --extract tepache_1.1-5_all.deb tepache_1.1-5_all
dpkg --control tepache_1.1-5_all.deb tepache_1.1-5_all/DEBIAN

Edit control file:
nano tepache_1.1-5_all/DEBIAN/control

Look for line that say:
Depends: python (>= 2.3), python-support (>= 0.7.1)

Change it to:
Depends: python (>= 2.3), python-support

Rebuld package:
dpkg --build tepache_1.1-5_all

Install package:
dpkg -i tepache_1.1-5_all.deb

This post has been edited by oshiri: Apr 10 2009, 03:09 PM
TSLaw
post Apr 10 2009, 01:57 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
Ok...thanks much..

I got found one application called kefir which is having similar functions as tepache.

I don't see any autoconnect function from the code sketched by tepache, but it was done with simple code.

This post has been edited by Law: Apr 10 2009, 02:09 PM
TSLaw
post Apr 10 2009, 02:35 PM

Getting Started
**
Junior Member
134 posts

Joined: Apr 2005
It shows me error:

dpkg-deb: failed to open package info file `tepache_1.1-5_all.deb/DEBIAN/control' for reading: Not a directory

i have checked on the directory, the file is exist.

so is it meant that this method doesn't work for me?

thanks...

This post has been edited by Law: Apr 10 2009, 02:39 PM

3 Pages  1 2 3 >Top
 

Change to:
| Lo-Fi Version
0.0273sec    1.31    6 queries    GZIP Disabled
Time is now: 17th December 2025 - 12:38 PM