G_S 38 Junior Poster in Training

Hello people,


I am currently working on a program for comparing texts. Everything is working fine thanks to your help.

However, I would like to have my program resize everything when the player resizes the main Window. I have managed to do so, but something feels amiss...


Can you help me with this issue? Here is the code:

import os
import platform
import webbrowser
from tkinter import *
import tkinter.ttk
import tkinter.filedialog
import tkinter.messagebox

def yview(*args):
    t1.yview(*args)
    t2.yview(*args)

main = Tk()
main.title("My Program")

if platform.system() == "Linux":
    color="light blue"
    width1 = 30
    width2 = 60
    style = tkinter.ttk.Style()
    style.theme_use("clam")

elif platform.system() == "Windows":
    color="light blue"
    width1 = 50
    width2 = 55

mainframe = tkinter.ttk.Frame(main, relief=GROOVE)
secondframe = tkinter.ttk.Frame(mainframe)
l1 = tkinter.ttk.Label(secondframe, text="Some text")
e1 = tkinter.ttk.Entry(secondframe, width=width1)
b1 = tkinter.ttk.Button(secondframe, text="Button")
l2 = tkinter.ttk.Label(secondframe, text="Sometext")
e2 = tkinter.ttk.Entry(secondframe, width=width1)
b2 = tkinter.ttk.Button(secondframe, text="Button")
l3 = tkinter.ttk.Label(secondframe, text="List")
c1 = tkinter.ttk.Combobox(secondframe, width=width1-3)
l4 = tkinter.ttk.Label(secondframe, text="List")
c2 = tkinter.ttk.Combobox(secondframe, width=width1-3)
thirdframe = tkinter.ttk.Frame(secondframe)
s1 = Scrollbar(thirdframe, orient=VERTICAL)
t1 = tkinter.Text(thirdframe, background="white", wrap=WORD, undo=TRUE, width=width2, yscrollcommand=s1.set)
t2 = tkinter.Text(thirdframe, background="white", wrap=WORD, undo=TRUE, width=width2, yscrollcommand=s1.set)
l5 = tkinter.ttk.Label(thirdframe, text="TEXT")
e3 = tkinter.ttk.Entry(thirdframe, width=width1)
b3 = tkinter.ttk.Button(thirdframe, text="Button")
b4 = tkinter.ttk.Button(thirdframe, text="Button")
b5 = tkinter.ttk.Button(thirdframe, text="Close", command=main.destroy)

s1.config(command=yview)

mainframe.grid(row=0, column=0, padx=5, pady=5, sticky=N+S+W+E)
secondframe.grid(row=0, column=0, columnspan=6, padx=5, pady=5, sticky=N+S+W+E)
l1.grid(row=0, column=0, pady=10)
e1.grid(row=0, column=1, pady=10)
b1.grid(row=0, column=2, pady=10)
l2.grid(row=0, column=3, pady=10)
e2.grid(row=0, column=4, pady=10)
b2.grid(row=0, column=5, pady=10)
l3.grid(row=1, column=0, padx=5)
c1.grid(row=1, column=1)
l4.grid(row=1, column=3, padx=5)
c2.grid(row=1, …
G_S 38 Junior Poster in Training

Yes, you are right. The problem was in the terminal program I was using, not python. I solved it by switching to Konsole.


Thank you all.

G_S 38 Junior Poster in Training

Hi,

a simple question: how do I enable deleting inside a python program?

I have a python program that asks for user input, users write some words and then press enter. The problem is they can't use backspace or supr to delete anything, instead, the program prints ^? each time they press backspace. Any ideas?


I use python 3.x and the readline libraries are working perfectly in the terminal program I use for running these scripts.


thank you

G_S 38 Junior Poster in Training

Hi,

this is, let's say, the second part of this thread: http://www.daniweb.com/forums/thread291657.html

I have managed to control two widgets with one scrollbar, but now I have realized that, althought the widgets can be controlled individually via the mouse wheel or the keyboard, I sometimes need individual controls for each widget.


This is tony's code from prevois thread:

try:
    from Tkinter import *
except ImportError: ## Python 3
    from tkinter import *

root = Tk()

class App:
    def __init__(self,master):
        scrollbar = Scrollbar(master, orient=VERTICAL)
        self.b1 = Text(master, yscrollcommand=scrollbar.set)
        self.b2 = Text(master, yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.b1.pack(side=LEFT, fill=BOTH, expand=1)
        self.b2.pack(side=LEFT, fill=BOTH, expand=1)
    
    def yview(self, *args):
        self.b1.yview(*args)
        self.b2.yview(*args)


app = App(root)

for item in range(0,40):
    for i in range(item):
        it=str(i)+' '
        app.b1.insert(1.0,it)
        app.b2.insert(1.0,it)
    app.b1.insert(1.0,'\n')
    app.b2.insert(1.0,'\n')
    
    
root.mainloop()

This is my try:

import tkinter.scrolledtext

try:
    from Tkinter import *
except ImportError: ## Python 3
    from tkinter import *

root = Tk()

class App:
    def __init__(self,master):
        scrollbar = Scrollbar(master, orient=VERTICAL)
        self.b1 = tkinter.scrolledtext.ScrolledText(master, yscrollcommand=scrollbar.set)
        self.b2 = tkinter.scrolledtext.ScrolledText(master, yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.b1.pack(side=LEFT, fill=BOTH, expand=1)
        self.b2.pack(side=LEFT, fill=BOTH, expand=1)
    
    def yview(self, *args):
        self.b1.yview(*args)
        self.b2.yview(*args)


app = App(root)

for item in range(0,40):
    for i in range(item):
        it=str(i)+' '
        app.b1.insert(1.0,it)
        app.b2.insert(1.0,it)
    app.b1.insert(1.0,'\n')
    app.b2.insert(1.0,'\n')
    
    
root.mainloop()

I changed the widgets to scrolled text idgets, but it causes a weird behavior in the scrollbar that affects both widgets.


Now, is there a way to scroll these widgets (either text or scrolledtext) without using a toolbar, for example, with buttons for up and …

G_S 38 Junior Poster in Training

Oh, nevermind (and sorry for the double post, I was unable to edit my previous post). I found out how to place it inside my code:

I just removed the 'self' keywords. The yview function in tonyjv's code is the magic behind the special scrollbar.


It's now working just as I need it to work. Thank you.

G_S 38 Junior Poster in Training

Oh, yes, like I said before, I had already found out how to get it to work with python 3.x. Actually, it was that same site where I found the information.

The question now is how to do it in the second block of code I showed you above.

And it is here where I need your help: I understand that the magic behind the scrollbar lies in "def yview". But I just can't figure out how to stick it inside my program since my approach seem very different.

(If I may ask a side question, why do some people make tkinter applications in that way? I see it's very different from my approach, (for instance, I never use clases) why is it about? Object oriented GUI making??? And then, what is the name of what I'm doing? Is it a mistake?)

G_S 38 Junior Poster in Training

Hello,


I need your help with something (again):

I need to control two text widgets with one scrollbar and, thanks to this website, I found some code to do it using listboxes (here: http://www.daniweb.com/forums/post940371.html#post940371). I modified it, and it now works with text widgets and pyton 2.x. The problem is: the code is too advanced, and I am unable to implement it within my program... besides, it only works in python 2.x.


I did some research and found out that the reason why it doesn't work with python 3.x is because of the changes in the apply function. So the questions are reduced to just one:

how can I implement the functionality in this code:

from Tkinter import *

root = Tk()

class App:
    def __init__(self,master):
        scrollbar = Scrollbar(master, orient=VERTICAL)
        self.b1 = Text(master, yscrollcommand=scrollbar.set)
        self.b2 = Text(master, yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.b1.pack(side=LEFT, fill=BOTH, expand=1)
        self.b2.pack(side=LEFT, fill=BOTH, expand=1)
    
    def yview(self, *args):
        apply(self.b1.yview, args)
        apply(self.b2.yview, args)


app = App(root)

for item in range(0,100):
    app.b1.insert(1.0,item)
    app.b2.insert(1.0,item)
    
root.mainloop()

into this one:

from tkinter import *

root = Tk()

scrollbar = Scrollbar(root, orient=VERTICAL)
text1 = Text(root, yscrollcommand=scrollbar.set)
text2 = Text(root)

scrollbar.config(command=text1.yview)

text1.grid(row=0, column=1)
text2.grid(row=0, column=2)
scrollbar.grid(row=0, column=3, sticky=N+S)
    
root.mainloop()

remember that the second code is python3.x code

G_S 38 Junior Poster in Training

Oh, of course, I forgot to tell you which toolkit I use. It's tkinter.

I managed to make the characters appear, but I need some way of making them appear as the user writes.

G_S 38 Junior Poster in Training

Nope, it's still not working...

The one I have (which works only under Linux) highlights the strings it finds, all of them at the same time, but your code only displays the position of the term's first character.

I tried to make it highlight the code above (the tag part), but it says invalid operand because pos is now an integer.

G_S 38 Junior Poster in Training

list.sort()? Is that what you are looking for?

Um, sorry, I don't understand. Could you explain what your code does?

The idea here was converting a string (which is visually presented as a list) into a python list, sorting it alphabetically, and then turning it back into a string.

this was done so that the user would get a list that loooks like a list to humans:

Aaaaaaaa
Bbbbbbbbbbb
Cccccccccc


and not a python list:

wich doesn't look like a 'human' list.

G_S 38 Junior Poster in Training

Ah!! But of course... Why didn't I see it...

Thanks :)

Any other suggestions???

G_S 38 Junior Poster in Training

Hi,

I have a Text widget and a button that is supposed to sort the Text's contents alphabetically.


This time I won't ask you how to do it, I'll rather ask you to correct me.

This is how I solved the problem:

unsortedT = text1.get(1.0, END).replace("\n", "\n*").split("*")
sortedT = sorted(unsortedT)
text1.delete(1.0, END)
text1.insert(END, "".join(sortedT))

by the way, the user is always told to write the contents in the following format:

word1
word2
word3

How bad/unelegant is it?

G_S 38 Junior Poster in Training

Oh I see, I learned somethin new again, love this place.

Um, but all of the above solutions have a problem: they lock the main program, and if you close the text version, the main program is also closed.

You see, there is a button that executes these functions. The idea is to be able to have the text version and use whenever you feel like it. If you close the text version, the graphical one should stay there in case you wanna continue working with it.

G_S 38 Junior Poster in Training

Oh... it was that simple, I feel dumb now...

Gotta read more about that startfile function, it's the second time that I saves me.

I assume this will also work on Linux right? If so this code is better than mine.

Thanks a lot, you are very helpful.

Oh, and congratulations, thi is your Nº 100 solved post :)

G_S 38 Junior Poster in Training

Hi,


I have a different question today:

how do I call the python interpreter AND tell it to open a python program from inside another program UNDER WINDOWS?

My program is running fine, and it even has a text mode without any graphical interface. Under Linux, you click on the 'text mode button', and it calls a console, which in turn calls python and tells it to open the program's non graphicl version.

Here is the code:

def textmode():
if os.name == "nt":
tkinter.messagebox.showwarning("Programmer error", "The programmer was not skilled enough to get this to work under Windows")
if os.name == "posix":
os.popen("xterm -geometry 160x40 -e python3.1 ./textversion.py")

as you can see, I'm calling xterm and telling it to open the text version. Now, how do I do it under windows? I have tried this:

c:\Program Files\Python3.1/python.exe ./textversion.py

but no luck...

G_S 38 Junior Poster in Training

Yes, it's working perfectly now. The trick was to change the type of error raised by the compiler function. It seems that SyntaxError's are not caught by except, at least not in this context.

G_S 38 Junior Poster in Training

What snippsat said is good,but what if I have several messages? One for each particular exception?

Gribouillis, thanks a lot man, you're really helpful. This works wonders.

G_S 38 Junior Poster in Training

Hi,

I've been working a lot with text widgets lately, and I have posted several questions here. Again, thanks for all your help.

This time I'd like to post something I found out, so you can help me improve it.


My program consists of two textboxes. The texts inserted in both are expected to have the same amount of paragraphs, if not, users are expected to modify them until this condition is met.

Now, to make things better for them, I decided to place a special character every time they press enter, in other words to have the program mark the end of a paragraph by inserting a particular character.

This is the code:

txt = open(file, "r") #don't forget to replace 'file' with the appropriate name
for line in txt.readlines():
    t1.insert(END, line.replace("\n","¶\n"))#t1 is the textbox

Now:

1. Is there a way to insert this thing = "¶" EVERY time the user presses enter (that would be replacing "\n" with ¶\n, but how do I tell the program to keep reading the widget and replacing?)

2. How do I give that character a red color. I know the fg="red" parameter, but it only works when I create the text widget.


thank you guys.

G_S 38 Junior Poster in Training

Thanks, it's what I needed

G_S 38 Junior Poster in Training

I did.

It seems the problem is Windows: the files I use have a lot of french and spanish characters, so the ansii encoding can't deal with them.

Texts are written in notepad, and the standard encoding is ansii. The problems are these:

1. If I save the file with ansii encoding, the program displays the special characters correctly, but if I open the xml file with firefox, it shows xml parsing errors due to the special characters.

2. Now, if I save the file with utf-8 encoding, the python program fails to display the special characters corectly.

This means that, somehow, the pyton program is reading ansii, but not utf-8.

G_S 38 Junior Poster in Training

Hi

I'm using python 3.1 and Windows.


My program writes xml code to a text file, the problem is that windows needs to know that this file's encoding is utf-8. Right now it does write the proper code, but other programs (firefox, for instance) fail to read it because it somehow got saved in the ansii encoding, which poses lot of problems when you use special characters.


Is there a way of getting python to write text to a file AND specify the encoding?


The program is running perfectly under Linux, as it is not that problematic with encodings, but I need to fix this problem under windows.


Thanks.

G_S 38 Junior Poster in Training

Hello,

I am making a file comparing program, and I want it to display line numbers permanently, like any normal text editor does. Is it possible to do this with tkinter?

thanks

G_S 38 Junior Poster in Training

Yes I know that, d5e5, but the error is clearly a SyntaxError (I think) because I made a test file with a broken print statement: print x (this is python 3.1).

the file:

x = "hello world"
y = "hello"
print x

The error in the terminal is this:

File "/home/mat/bin/frontends/bad.py", line 3
    print x

File "/home/an/bin/PyCompiler/malo.py", line 3      
    print x
          ^
SyntaxError: invalid syntax

^

G_S 38 Junior Poster in Training

Hi,

I'm trying to make a frontend for the compile module in python.

Everything works just right, except when the file has mistakes in the code that lead to a syntax error.

It does raise the invalid syntax error in the terminal, but instead of executing the block inside the except statement, it goes on to the else block. look:

try:
        file = t1.get()
        py_compile.compile(file)
    except IOError:
        tkinter.messagebox.showerror("Error", "File not found")
    except UnicodeDecodeError:
        tkinter.messagebox.showerror("Error", "This is not python code")
    except SyntaxError:
        tkinter.messagebox.showerror("Error", "There is a syntax error in the code")
    else:
        time.sleep(2)
        tkinter.messagebox.showinfo("¡Successfully compiled!", "The file \n(%s)\n was compiled successfully" %file)
G_S 38 Junior Poster in Training

This works wonder. Thanks a lot. Something must be wrong with this poarticular Windows configurations since it doesn't open the default browser but rather explorer all the time. But your code works on Linux and Windows as expected (and somehow manages to open the real default browser).

Tha you all for your help.

G_S 38 Junior Poster in Training

That's prety useful, as I'm also learning Java. Thanks again.

G_S 38 Junior Poster in Training

hmmm, how do you use these class guys?

I still do not know object oriente programming, my program is event-oriented.

Can I copy that code and leave it inside a separate file, then import it into my program?

If so, how do I make a widget in my program using that class?

G_S 38 Junior Poster in Training

The question is simple:

I have two scrolled text widgets (I'm using tkinter and python 3.x), and I want to synchronize them, that is I want both scrollbars to move at the same time when the user moves the mouse wheel.

Both widgets are suppossed to contain the same text, and the user is going to compare the information in both, so it is necessary that he can scroll both boxes at once.


Thanks.

G_S 38 Junior Poster in Training

OK, I understand now. It's working perfectly. Thak you guys, you're realy helpful.

G_S 38 Junior Poster in Training

This makes a lot of sense, it is basically comparing two lines of text to see if they are the same text, if they are, the line won't be including in the merged file. Thanks to you I was able to finish the program easily. Thanks you very much.

G_S 38 Junior Poster in Training

OK, Solved, that's a good example. I also found the map method, which helps you modify things, but it's too complicated.

What snippsat said is not tru for windows anymore. On Linux, though, tkinter looks horribly simple and old, but on Windows, tkinter looks native!! This is unconceivable, but sad and true...

G_S 38 Junior Poster in Training

Great, it worked.

Can you explain to me what this line of code means (what the program is doing here):

if text0.strip() == text2[(text1.index(text0))].strip():
pass

particularly the part between brackets.

G_S 38 Junior Poster in Training

Hello,


I've been looking for this here but haven't been able to find an answer that fits my case:

I have a tkinter GUI consisting in a button and a Text (a textbox). You write the whole text in the textbox, then press the button and it uses the get() method on the textbox. Now, here comes the problem: get() returns a big string, and I need a list. How do I turn the information in the textbox into a list?

I am trying to make a GUI for someone else's code. In that program, the text is not inserted into a textbox (because there's no GUI) but rather into a file. The program then uses a for statement and the readlines() method to sucessfully separate the text into smaller chunks.

The problem is that, in my case, the parsing function is getting a single string, not a list, so it's not working at all.

any help would be appreciated.

G_S 38 Junior Poster in Training

Yes, it works on Linux, but on Windows 7, it's opening iexplorer and telling it to go to http://./html/index.html

Thi is how it works on my windows 7:

* default browser is firefox
* if I write webbrowser.open('./index.html'), it opens explorer and tries to open http://./index.html
* if I write webbrowser.open('C:/ABSOLUTE PATH/index.html'), it does open the default browser (firefox) with the correct url.

What is going on???

G_S 38 Junior Poster in Training

OK, I'll try that.

One more question: I want to open a local file with the browser. Is it possible to use arelative path? I wouldn't know where the user places the folder, so the path to the html file has to be relative.

G_S 38 Junior Poster in Training

Oh, wait, it's not completely solved:

on linux, everything is fine.

on windows, however, webbrowser.open only opens Explorer, even though firefox is the default.

If I try startfile, it does open the associated program as d5e5 explained, but it fails to open the help file (it seems it only works with URL's)

G_S 38 Junior Poster in Training

Hmmm,maybe I did not understand properly... what is the behavior you are expecting? You want the windows to be "un-iconifiable" so that it can never be minimized?

G_S 38 Junior Poster in Training

Here is your example:

from tkinter import *

def name():
    name = entry.get()
    text.delete(1.0, END)
    text.insert(END, "Hello " + name + "!")

main = Tk()
main.geometry("400x400")
main.resizable(0, 0)
main.wm_attributes("-topmost", 1)

label = Label(main, text="What's your name?")
entry = Entry(main)
button0 = Button(main, text="Say hello!", command=name)
button1 = Button(main, text="close", command=quit)
text = Text(main)

label.pack()
entry.pack()
button0.pack()
button1.pack()
text.pack()

main.mainloop()

Also, you can place the main.wm_attributes stuff inside a function and then create a binding to a keyboard shortcut, for example ctrl+t. Then the program would stay on top of the others after you press the shortcut. In this example, the window will always be on top.

G_S 38 Junior Poster in Training

Let me see if I got this right:

os.startfile("PATH OR URL") would open the defaultbrowser for windows and send it there?

and

webbrowser.open("PATH OR URL") would do the same but for any platform?


can you clarify why they are so different?? Which one is better???

G_S 38 Junior Poster in Training

Well, if you don't mind the looks, tkinter is the built-in graphical toolkit for python, so it is cross platform and the user would have to install anything besides python itself.

Regarding the code, this would cause the window (named main in this case) to be always on top:

main.wm_attributes("-topmost", 1)

If you need a full example with tk widgets let me know, I have plenty of them here.

G_S 38 Junior Poster in Training

Hi people,

the title says it all:

The user manual of my program is an HTML document, and I want the OS's default browser to open it directly once the user clics on help.


The function that the help menu entry invokes is this:

os.popen("/usr/local/firefox/firefox ./html/index.html")

Now this only works on Linux and because I know where the firefox executable is. Is there a way of calling the default browser? And how would I do it on Windows?

Remember that I want the function to call the browser and also tell it what file it should open.

Thanks in advane

G_S 38 Junior Poster in Training

Ok I see, what about else? It can follow either an if or an elif, right?

G_S 38 Junior Poster in Training

I'll try that...

G_S 38 Junior Poster in Training

Whoan, what are all those letters?


I tested it and it works, I'm also trying to find more information. It seems there is a way to modify particular options if an existing theme.

G_S 38 Junior Poster in Training

Oh! I see now. Excellent explanation, thank you. So, after all there is a slight difference in that elseif does not pair up with anything?

G_S 38 Junior Poster in Training

yes, yes I understand that, but if you check my code you'll see that two ifs in Linux will output BOTH Linux and there is a problem, whereas one if, one elif and one else will only output Linux, which should be the case...

G_S 38 Junior Poster in Training

Ok, I get the if and elif stuff, now, why is it printing both values if OS is supposed to be posix an only posix? And why is it solved with elif, if, as you say it's supposed to mean the same as if-if?

G_S 38 Junior Poster in Training

Hi,

I have a very simple question:


first of all, my code:

import os

def test():
    x = "Linux"
    y = "Windows"

    if os.name == "posix":
        print(x)
    if os.name == "nt":
        print(y)
    else:
        print("there is a problem")

Run that code on Linux (don't know about windows) and it'll print both Linux and there is a problem.

Now do this:

import os

def test():
    x = "Linux"
    y = "Windows"
     if os.name == "posix":
        print(x)
    elif os.name == "nt":
        print(y)
    else:
        print("there is a problem")

This time it'll work perfectly. The question is: why does it work with elif but not with two if's?

I was told that it was the same, only that elif is more elegant, but know I see there must be a difference. Any thoughts?


Thank you

G_S 38 Junior Poster in Training

Hi,

I have a minor quesion today: can somebody tell me how to change basic style options for buttons using ttk.

I'd like my buttons and entry fields to have rounded corners. I know this is possible but documentation on ttk (for python) seems to be inexistent on the Web. I haven't been able to find a tutorial on ttk widget styles.


Thank you

G_S 38 Junior Poster in Training

Thank you very much Gribouillis, that is exactly what I was looking for. That piece of code covers my needs perfectly.