简体   繁体   中英

Making a chat client window

I'll start with code

import socket;
from Tkinter import *;

#Initalize tkinter
root = Tk();
App = root;
root.title("Client");
root.configure(bg = "#DEE2E3");
App.geometry("400x450");

#Input
typeBox = Entry(root, text = '');
send = Button(root, text = 'Send', bg = "#A0DEF2", font = ('times', 14, 'bold'));
typeBox.pack(side = BOTTOM, fill = X);
send.pack(side = BOTTOM, fill = X);

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
host = 'localhost';
port = 5500;

#connect to server
s.connect((host, port));

#chat
while(True):
    message = raw_input("Message: ");
    s.send(message);
    data = s.recv(1024);
    print(data);

root.mainloop();

I want to get the information from the entry widget. Then when click send I want it to show on the client and sends to server.(I've changed message to equal typeBox,but then it spams data sent in server.)

The while loop runs forever, that is why it spams when you don't have the raw_input to pause the spam. You need to put that code into a function (without the while loop), that function can then be assigned as the command for the button.

def cmd_send():
    message = typeBox.get()
    s.send(message)
    data = s.recv(1024)
    print(data)

This function needs to be defined sometime before you create the send Button. To add this as a command to the button, include the option:

command = cmd_send

So for your button it would turn out to be:

send = Button(root, text = 'Send', bg = "#A0DEF2", font = ('times', 14, 'bold'), command = cmd_send)

And get rid of all the ; at the end of your lines ;-)

EDIT:

Add a Text widget to display your message. Since I don't have the server code, I have only tested inserting directly. You can add a Text widget like:

output = Text(root, font=('times', 14))
output.pack(side=TOP, fill=X)

This could be inserted at the same place you make and pack the Entry and Button widgets. Then replace print(data) in the cmd_send function with:

output.insert(END, data + "\n")

This will insert the data you receive at the end of the Text Widget, and add a newline. New Mexico Tech has a good reference for Tkinter . And TkDocs also have some nice info.

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