簡體   English   中英

Python GTK GUI出現

[英]Python GTK GUI struck

我正在使用python gtk通過boto API將文件上傳到S3服務,上傳文件時GUI被擊中,並在完成上傳過程后釋放GUI,我使用線程顯示GUI中的上傳進度,但是被擊中。 您能否提出一些建議,說明如何在GUI或任何微調器中顯示上傳進度,直到上傳完成。 我是python的新手,您能否建議如何也將線程用於GUI。

#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto.exception import S3ResponseError, S3CreateError
import threading
import random, time
gtk.threads_init()

class FractionSetter(threading.Thread):
    """This class sets the fraction of the progressbar"""

    #Thread event, stops the thread if it is set.
    stopthread = threading.Event()

    def run(self):
        """Run method, this is the code that runs while thread is alive."""

        #Importing the progressbar widget from the global scope
        global progressbar 

        #While the stopthread event isn't setted, the thread keeps going on
        while not self.stopthread.isSet() :
            # Acquiring the gtk global mutex
            gtk.threads_enter()
            #Setting a random value for the fraction
            progressbar.set_fraction(random.random())
            # Releasing the gtk global mutex
            gtk.threads_leave()

            #Delaying 100ms until the next iteration
            time.sleep(0.1)

    def stop(self):
        """Stop method, sets the event to terminate the thread's main loop"""
        self.stopthread.set()




class SampleGUI:

    def destroy(self,widget,data=None):
        global fs
    fs.stop()
        gtk.main_quit()

    def get_relative_filename(self, filename):
        f_parts = filename.split('/')
        return f_parts[len(f_parts) - 1]
    def browse(self,widget):
        chooser1 = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        chooser1.set_show_hidden(True)
        response1 = chooser1.run()
        if response1 == gtk.RESPONSE_OK:
            global filename1
            filename1 = chooser1.get_filename()
            self.textbox.set_text(filename1)
            print filename1
        elif response1 == gtk.RESPONSE_CANCEL:
            chooser1.destroy()

        chooser1.destroy()
    def ensure_bucket(self,connection, bucket, canned_acl=None):
        bucket_instance = None


        try:
            print 'Checking bucket:', bucket
            bucket_instance = connection.get_bucket(bucket)
        except S3ResponseError, s3error:
            s3error_string = '%s' % s3error
            if s3error_string.find('404') >= 0:
                try:
                    bucket_instance = self.create_bucket(connection, bucket,
                            canned_acl)
                except S3CreateError:
                    print 'Unable to create bucket %s' % bucket
                    message1 = gtk.MessageDialog(type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK)
                    msgg = "Unable to create bucket "+bucket
                    message1.set_markup(msgg)
                    message1.run()
                    message1.destroy() 
            elif s3error_string.find('403') >= 0:
                message1 = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK)
                msgg = "You do not have permission to access bucket"
                message1.set_markup(msgg)
                message1.run()
                message1.destroy() 
                d.hide()
                d.destroy()
                print 'You do not have permission to access bucket:', bucket

            else:
                print s3error_string
                sys.exit()
        return bucket_instance

    def upload_file(self,bucket_instance, filename,
                        canned_acl=None):
        fs = FractionSetter()
        global fs
        fs.start()

        print 'Uploading file'
        print "file name",filename
        k = Key(bucket_instance)
        k.key = self.get_relative_filename(filename)
        m_file = open(filename, 'rb')
        print filename
        try:
            k.set_contents_from_file(m_file,policy=canned_acl)
            fs.stop()
        except S3ResponseError, s3error:
            s3error_string = '%s' % s3error
            if s3error_string.find('403') >= 0:
                print 'Permission denied while writing:', k.key
            else:
                print s3error_string
            sys.exit()

    def submitt(self,widget):
        print "submitt"
        global filename1
        print "file name",filename1
        conn = boto.s3.connection.S3Connection(
                   aws_access_key_id='WKy3rMzOWPouVOxK1p3Ar1C2uRBwa2FBXnCw',
                   aws_secret_access_key='UmMJCdlCXvW9DJOgN2MkTOmEXJJKcQu62bFWg',
                   is_secure=False,
                   host="10.184.39.113",
                   port=8773,
                   calling_format=boto.s3.connection.OrdinaryCallingFormat(),
                   path='/services/Walrus',
                   )
        print conn
        bucket_instance = self.ensure_bucket(conn, "sample", canned_acl=None)
        print bucket_instance
        self.upload_file(bucket_instance, filename1, canned_acl=None)
    def pageChanged(self,notebook,page,page_num):
        print "ClickedMe called for"


    def __init__(self):

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.window.set_size_request(600,400)
        self.window.set_title("UPLOAD A OBJECT TO S3")
        self.window.set_resizable(False)

        self.button1 = gtk.Button("Browse")
        self.button1.connect("clicked",self.browse)

        self.button2 = gtk.Button("Submit")
        self.button2.connect("clicked",self.submitt)

        self.textbox = gtk.Entry()

        self.label1 = gtk.Label("<b>Upload objects to S3</b>")
    self.label1.set_use_markup(True)
        self.table = gtk.Table(5, 5, True)


        notebook = gtk.Notebook()
        notebook.set_tab_pos(gtk.POS_TOP)
        notebook.connect("switch-page",self.pageChanged)
        page1 = gtk.Frame(label=None)

        self.table.attach(self.label1, 1, 4, 1, 2)
        self.table.attach(self.textbox, 1, 4, 2, 3)
        self.table.attach(self.button1, 4, 5, 2, 3, xpadding=20, ypadding=20)

        self.table.attach(self.button2, 4, 5, 3, 4,xpadding=20, ypadding=20)        
        global progressbar
        progressbar = gtk.ProgressBar()
        self.table.attach(progressbar, 0, 5, 4, 5, xpadding=20, ypadding=20)
        page1.add(self.table)

        notebook.append_page(page1,gtk.Label('Upload Files'))
        self.window.add(notebook)
        self.window.show_all()
        self.window.connect("destroy",self.destroy)


    def main(self):
        gtk.main()
        fs = FractionSetter()
        global fs
        fs.start()


if __name__ == "__main__":
    base = SampleGUI()
    base.main()

這可能有幫助

請遵循Pygtk常見問題解答http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp

您可能必須在代碼中添加以下兩行以繼續進行主要迭代

while gtk.events_pending():
    gtk.main_iteration()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM