简体   繁体   中英

Python Tkinter StringVar() issues

I am fairly new to coding and most of the time I am researching as I go on how to write things. I am stumped at trying to get this label to update and I think it is because I am trying to change the StringVar() in a place I cannot.

Anyway the following is my code, sorry if it is ugly. I would appreciate any advice but most importantly I need the Label(connection_window, textvariable=isconnected).grid(row=3) to update when I change the StringVar() variable.

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

First, by typing isconnected = "worked" , you're re-binding isconnected to something other than the StringVar you set it to at the top. That's going to be a problem. You probably mean something like isconnected.set("worked") .

Second, something like

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

will make it so the label is updated whenever the stringvar is changed.

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