shahar
shahar

Reputation: 79

How to create a chat window with tkinter?

I tried to create a chat window and it does not work right. Every time I enter the message it's popping up and increases the window. What should I do?

from Tkinter import *

window = Tk()

input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)

def Enter_pressed(event):
    input_get = input_field.get()
    print(input_get)
    label = Label(window, text=input_get)
    input_user.set('')
    label.pack()
    return "break"

frame = Frame(window, width=300, height=300)
input_field.bind("<Return>", Enter_pressed)
frame.pack()

window.mainloop()

Upvotes: 3

Views: 12729

Answers (3)

T. Balan
T. Balan

Reputation: 1

Try using a more simple approach (Python 3.7.3)

from tkinter import *
root = Tk()
root.resizable(height = False, width = False)
root.title('Chat Window Thingy')

l1 = Label(root, text = 'Your Text Here',fg='green').pack()
e1 = Entry(root, text = 'Your text here').pack()

root.mainloop()

I am a Year 10 Computer Science student so be gentle, but I hope that this solved your problem :)

Upvotes: 0

j_4321
j_4321

Reputation: 16169

Your problem is that the labels you create have window as parent instead of frame, so they are packed below frame, not inside:

from Tkinter import *

window = Tk()

input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)

def enter_pressed(event):
    input_get = input_field.get()
    print(input_get)
    label = Label(frame, text=input_get)
    input_user.set('')
    label.pack()
    return "break"

frame = Frame(window, width=300, height=300)
frame.pack_propagate(False) # prevent frame to resize to the labels size
input_field.bind("<Return>", enter_pressed)
frame.pack()

window.mainloop()

But if you want to be able to scroll your messages, I agree with Steven Summers and WaIR, you should use a Text widget.

Upvotes: 3

Kenly
Kenly

Reputation: 26748

You are adding a label each time you press enter, try showing messages in a Text widget:

from Tkinter import *

window = Tk()

messages = Text(window)
messages.pack()

input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)

def Enter_pressed(event):
    input_get = input_field.get()
    print(input_get)
    messages.insert(INSERT, '%s\n' % input_get)
    # label = Label(window, text=input_get)
    input_user.set('')
    # label.pack()
    return "break"

frame = Frame(window)  # , width=300, height=300)
input_field.bind("<Return>", Enter_pressed)
frame.pack()

window.mainloop()

Upvotes: 4

Related Questions