user3780539
user3780539

Reputation: 47

need display to be on 3 lines not 1 line

My desired outcome is to have a python window with two buttons "Show Info" "Quit" next to each other and have the "Show Info" button display my name and address on 3 separate lines and then stop the program when "Quit" is clicked. I'm almost there - the text is all coming on one line though.

thanks in advance.

# This program will demonstrate a button widget within a dialog box
# that shows my information.

# Call TK interface
import tkinter
# Call message box
import tkinter.messagebox

# Create class for GUI.


class MyGUI:
    def __init__(self):
        #Create the main window widget.
        self.main_window = tkinter.Tk()

        #Create button widget 1.
        self.my_button = tkinter.Button(self.main_window, \
                                        text='Show Info', \
                                        command=self.show_info)

        #Creat a quit button.
        self.quit_button = tkinter.Button(self.main_window, \
                                          text='Quit', \
                                          command=self.main_window.destroy)

        # Pack the buttons.
        self.my_button.pack(side='left')
        self.quit_button.pack(side='left')

        #Enter the tkinter main loop.
        tkinter.mainloop()

        #The do_somethings will be defined.
    def show_info(self):
        tkinter.messagebox.showinfo('Text', \
                                    'My Name'
                                    '123 Any Rd'
                                    'Town Fl, 12345')




my_gui = MyGUI()

Upvotes: 4

Views: 15804

Answers (4)

furas
furas

Reputation: 142631

Add \n in your text

tkinter.messagebox.showinfo('Text','My Name\n123 Any Rd\nTown Fl, 12345')

Upvotes: 1

user2555451
user2555451

Reputation:

It may seem simple, but for such few lines, the most elegant solution is to just end each one with a newline character (\n):

def show_info(self):
    tkinter.messagebox.showinfo('Text',
                                'My Name\n'
                                '123 Any Rd\n'
                                'Town Fl, 12345\n')

If you have many lines though (such as a paragraph), you can use a multi-line string:

    def show_info(self):
        tkinter.messagebox.showinfo('Text', '''\
My Name
123 Any Rd
Town Fl, 12345''')

Upvotes: 5

og1L
og1L

Reputation: 111

Just need to add some newline-characters (\n) to your infotext. Just writing it over multiple lines doesn't make it a multi-line text.

Upvotes: 1

Ajean
Ajean

Reputation: 5659

The line breaks where you have defined your 3 lines don't do what you think ... Python will smash those strings together as if there was no return there at all (which is what you are seeing). Instead, try putting this there:

def show_info(self):
    lines = ['My Name', '123 Any Rd', 'Town Fl, 12345']
    tkinter.messagebox.showinfo('Text', "\n".join(lines))

Upvotes: 7

Related Questions