简体   繁体   中英

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()

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()

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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM