Python Tkinter字符串变量问题

2024-04-20 00:43:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编码相当陌生,大部分时间我都在研究如何写东西。我很难让这个标签更新,我想这是因为我试图改变StringVar()在一个我不能改变的地方。在

不管怎样,下面是我的代码,抱歉,如果它是丑陋的。如果有任何建议,我将不胜感激,但最重要的是,当我更改StringVar()变量时,我需要Label(connection_window, textvariable=isconnected).grid(row=3)进行更新。在

import socket
import sys
from Tkinter import *

root = Tk()


ip_entry = None
port_entry = None
isconnected = StringVar()

try:
    mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print ("failed to create socket")
    sys.exit()

def start_connection_window():
    connection_window = Toplevel(root)
    global ip_entry
    global port_entry
    global isconnected

    Label(connection_window, text = "Host IP Address:").grid(row=0)
    Label(connection_window, text = "Host Port #:").grid(row=1)

    ip_entry = Entry(connection_window)
    port_entry = Entry(connection_window)
    connect_button = Button(connection_window, text="connect", width=15, command=connect)

    ip_entry.grid(row=0, column=1)
    port_entry.grid(row=1, column=1)
    connect_button.grid(row=2, column=0, columnspan=2)
    Label(connection_window, textvariable=isconnected).grid(row=3)

def connect():
    global ip_address
    global port_number
    global isconnected
    isconnected = "worked"
    ip_address = ip_entry.get()
    port_number = port_entry.get()
    try:
        mysock.connect((ip_address,port_number))
        print("connected to",ip_address,port_number)
    except:
        isconnected.set("unable to connect")

open_connection = Button(root, text="Connection setup", width=15, height=3, command=start_connection_window)

Label(root, text = "Jason's Watering System", width=100).grid(row=0,column=0,columnspan=2)
open_connection.grid(row=0, column=2)

"""
mysock.sendall(message)
"""

mysock.close()
root.mainloop()

Tags: textipportconnectcolumnrootsocketconnection
1条回答
网友
1楼 · 发布于 2024-04-20 00:43:53

首先,通过键入isconnected = "worked",您将isconnected绑定到与顶部设置的StringVar不同的内容。那会是个问题。你可能是说isconnected.set("worked")。在

第二,有点像

mylabel = Label(connection_window, textvariable=isconnected)
mylabel.grid(row=3)
isconnected.trace("w", mylabel.update) # w = "changed"

每当stringlabel被更改时,var将使其更新。在

相关问题 更多 >