Search code examples
pythontkintertwistedtextfieldreactor

Writing dataReceived (from Twisted) to a tkinter texxtbox


Okay, so I'm sure this should be more simple than it is, but... Basically, I have a twisted reactor listening on a specific port. I also have a tkinter form containing a textbox. What I want to do is simply write the data received to that textbox.

Below is what I have so far:

from twisted.web import proxy, http
from twisted.internet import reactor
from twisted.python import log
import ScrolledText
import sys
#Gui stuff
from Tkinter import *
import ttk
import Tkinter as tk
from ScrolledText import *
import tkMessageBox
from twisted.internet import tksupport

root = Tk()
class MyProxy(proxy.Proxy):
    def dataReceived(self, data):
       print data
       textfield.delete(0,END)
       textfield.insert(0, data)
       textfield.pack()
       return proxy.Proxy.dataReceived(self, data)

class ProxyFactory(http.HTTPFactory):
    protocol=MyProxy

def guiLoop():
    print "[+] Drawing GUI"
    menubar = Menu(root)
    connectMenu = Menu(menubar, tearoff=0)
    connectMenu.add_command(label="Help")  
    connectMenu.add_command(label="About")
    menubar.add_cascade(label="Proxy", menu=connectMenu)
    root.minsize(300,300)
    root.geometry("500x500")
    root.textfield = ScrolledText()
    root.textfield.pack()
    #top = Tk()
    root.title("Proxy")
    root.config(menu=menubar)
    tksupport.install(root)

def main():
    #runReactor()
    factory = ProxyFactory()
    reactor.listenTCP(8080, factory)
    reactor.callLater(0, guiLoop)
    print "[+] Starting Reactor"
    reactor.run()

if __name__ == "__main__":
    main()

I've looked around, but there doesnt seem to be a clear way showing how to write to a textbox from a different function.


Solution

  • There's nothing special -- you just need a reference to the widget, or call a function that has a reference to the widget.

    Since root is global, and the text widget is an attribute of root, you should be able to do something like:

    root.textfield.delete("1.0", "end")
    root.textfield.insert("1.0", data)