How do you pprint a obj.lookup() into a Tkinter textbox - python

I've been trying to print the results of an ipwhois lookup into a Tkinter textbox but it's not working.
Currently i Get this error: TclError: wrong # args: should be ".40872632.46072536 insert index chars ?tagList chars tagList ...?"
Here's my code:
result2=unicode(set(ipList).intersection(testList));
result3=result2[:19].strip()
result4=result3[6:]
obj = ipwhois.IPWhois(result4)
results = obj.lookup()
results2= pprint.pprint(results)
text = Tkinter.Text(self)
text.insert(Tkinter.INSERT, results2)
text.insert(Tkinter.END, "")
text.pack()
text.grid(...)``
How do I pprint or at least split the results string by newline and why does it not work?

The issue here is that when you are trying to get the pprinted value of results2, it's returning None because pprint just writes the output to sys.stdout. When you then go on to do text.insert(Tkinter.INSERT, None) it throws the error that you keep receiving. This basically means you need to find another way to get the formatted string of your list - I'd recommend "\n".join(results).
As a side note, unless self is a Tkinter.Tk() or Tkinter.Toplevel() or something of the sort, you shouldn't have it as the text widget's parent. On top of that, you can cut and shorten the code you have above to the following:
results2 = "\n".join(results)
text = Tkinter.Text(self)
text.insert(Tkinter.END, results2) # Write the string "results2" to the text widget
text.pack()
# text.grid(...) # Skip this, you don't need two geometry managers
Check this out to read more about Tkinter - it's a really great resource for Tcl/Tk reference.

Related

Creating tag names for installed fonts and displaying font name in font style

I have written this code to get a list of installed fonts on my system, which should then create a text widget with all the fonts displayed. However, I find that some of the fonts in the list are named but not displayed correctly. They are not 'clickable' so I guess that a tag has not been created for that item. Anyone have an idea why this would be?
import tkinter as tk
from tkinter import *
from tkinter import font
def on_click(event):
fontname=display.index('#{},{}'.format(event.x,event.y))
print (display.tag_names(fontname))
return None
root = Tk()
fonts=list(font.families())
fonts.sort()
display = Text(root)
display.pack(fill=BOTH, expand=YES, side=LEFT)
scroll = Scrollbar(root)
scroll.pack(side=RIGHT, fill=Y, expand=NO)
scroll.configure(command=display.yview)
display.configure(yscrollcommand=scroll.set)
for item in fonts:
i=fonts.index(item)
i+=1
i=str(i)
display.tag_add (item, ('{}.0'.format(i)) ,END)
display.tag_config(item,font=(item,25,'normal'))
display.tag_bind(item,'<Double-1>',on_click)
display.insert(END, (item +'\n'),(item))
root.mainloop()
my output for example 'Arial Black' is ('Arial', 'Black')
but for 'Comic Sans MS' I get nothing. By passing 'font=(item,15,'normal) spaces should not be an issue or did I misread that? or could it be the way the font titles are formatted in the font file? This is all new to me the last time I did any coding it was on a zx81
The problem is that the tags given for the insert statement needs to be a list. You are using (item) which, I'm guessing, you think is a one-item tuple. It is not a tuple, it's just a string expression. For it to be a tuple it needs a comma (eg: (item,)).
Thus, what is getting passed to the widget is something like "DejaVu Sans Mono". The underlying tcl interpreter sees this as a list of three tags: "DejaVu", "Sans", and "Mono".
To pass a proper list, either use brackets or include a comma to change your expression into a tuple.
Notice in the following example, the command at the end of (item,).
display.insert(END, (("%s: " % i) + item +'\n'),(item,))

How to combine two strings to describe a property of tree.insert?

I'm creating a gui with tKinter, working with python for the first time.
Part of my gui is a treeview, the nodes in the treeview have images attached.
I made a function to add new nodes to the treeview.
I want to add an image to the new node based on the mother of the node.
In this case The variable 'curItem' returns the mother as a string, "test" in this case.
I want to combine the string "photo_" and "test" and use this in the 'tree.insert' code.
But for this to work I have to convert the string to something else, but I dont know to what and how to do this.
This is probably a very basic question, but I have been unable to find an answer so far.
Part of the relevant code:
photo_test = PhotoImage(file="resources/test.png")
def add():
curItem = tree.selection()[0] #returns "test"
img = "photo_" + curItem
tree.insert(curItem, 'end', text='new', image=img) #doesn't work
tree.insert(curItem, 'end', text='new', image=photo_test) #works
You're trying to set the image to the string 'photo_test'. Try storing the actual photo in a dict and access it via the string, something like this.
photos = dict()
photos["photo_test"] = PhotoImage(file="resources/test.png")
def add():
curItem = tree.selection()[0] #returns "test"
img = "photo_" + curItem
tree.insert(curItem, 'end', text='new', image=photos[img])
You seems to have misunderstood the difference between a variable and a string though. A string is just text within the code, not actually code, so you can't pass a variable name in string form and expect the code to read that value. "photo_test" is not the same as photo_test.

Tkinter Find and Replace Function for Notepad

I'm new at Tkinter, and python. I've been experimenting with a notepad script I've made. I'm working on a find / replace command. But I've had no luck. Here is what I've tried so far:
def replace():
def replaceall():
findtext = str(find.get(1.0, END))
replacetext = str(replace.get(1.0, END))
alltext = str(text.get(1.0, END))
alltext1 = all.replace(findtext, replacetext)
text.delete(1.0, END)
text.insert('1.0', alltext1)
replacebox =Tk()
replacebox.geometry("230x150")
replacebox.title("Replace..")
find = Text(replacebox, height=2, width=20).pack()
replace = Text(replacebox, height=2, width=20).pack()
replaceallbutton = Button(replacebox, text="Replace..", command=replaceall)
replaceallbutton.pack()
(this is just the function I am defining for the replace command)
The 'text' variable is on the large canvas which contains the menu's and the main text widget.
Any help is appreciated
So far I've been creating this notepad in 2.7.8, so the Tkinter import is 'Tkinter.'
What I'm shooting for is having the first box have the text to find and the second box have the text to be replaced. Upon pressing the replace button, the function replaceall() should begin.
Are there any obvious mistakes in my function, or is it just deeply flawed? Any help is appreciated.
The most obvious mistake is that you are creating a second instance of Tk. If you need a popup window you should create an instance of Toplevel. You should always have exactly one instance of Tk running.
The second problem is related to the fact you are using a Text widget for the find and replace inputs. When you do a get with a second index of END, the string you get back will always have a newline whether the user entered one or not. If you want exactly and only what the user typed, use "end-1c" (end minus one character).
Finally, there's no reason to get all the text, replace the string, and then re-insert all the text. That will work only as long as you have no formatting or embedded widgets or images in the text widget. The text widget has a search command which can search for a pattern (either string or regular expression), and you can use the returned information to replace the found text with the replacement text.

python text widget get method

I have a text widget in my python Tkinter script and i am trying to get the value that the user enter. My intention is to write the data from the text widget together with other values from the script(ie. x,y,z) to the txt file(faultlog.txt) as a single line with semi-column separated. This is what i tried.
...
text=Text(width=30,height=1)
text.place(x=15,y=75)
data=text.get(1.0,END)
lines=[]
lines.append('{};{};{};{} \n'.format(data,x,y,z))
faultlog=open("faultlog","a")
faultlog.writelines(lines)
faultlog.close()
...
Instead of giving me a single line output in the text file, python is writing this to the txt file (assuming the data that user enter is "abcdefgh")
abcdefgh
;x;y;z
just to make things clear, this is what i want
abcdefgh;x;y;z
What did i do wrong? I hope the question is clear enough, i am a beginner so please make the answer simple.
When you get all text of the widget, there is also included a "\n" at the end. You can remove this last character like this:
data=text.get(1.0,END)[:-1]
Note that this always works independently of the length of the text length:
>>> "\n"[:-1]
''
>>> ""[:-1]
''

Select text of textEdit object with QTextCursor, QTextEdit

I have a textEdit field and I want to process some selected text within this field (but not the format of it).
So far, I connect the button with:
QtCore.QObject.connect(self.ui.mytext_button,QtCore.SIGNAL("clicked()"), self.mytext)
The method:
def mytext(s):
return s.upper()
But how do I tell Python that s is the selected text? I know that is something with selectionStart(), selectionEnd(). And how to change it to what mytext returns? I think is something with insertText(), but here I am also lost at the details.
Answering my own question. Posting here for fellow Python noobs:
Get the selected text:
cursor = self.ui.editor_window.textCursor()
textSelected = cursor.selectedText()
insert back the text into your editor.
self.ui.editor_window.append(s)
There are also alternatives to append(), for inserting the text into the original text.
So, to put a selected text into uppercase:
def mytext(self):
cursor = self.ui.editor_window.textCursor()
textSelected = cursor.selectedText()
s = textSelected.upper()
self.ui.editor_window.append(s)

Categories

Resources