Python Tkinter:使用Entry重置先前定义的变量

时间:2014-07-31 18:06:42

标签: python tkinter connect irc

我正在尝试这样做,以便当用户输入他们的名字,密码等时,它会全局存储它,以便程序能够连接该名称。我已经在这里定义了变量:

global server
server = ""
global nick
nick = ""
global altnick
altnick = ""
global password
password = ""
global channel
channel = ""

然后,当Tkinter程序进入时,用户可以使用条目输入所有正确的值:

networktop = Toplevel(master=root)
networktop.title("Network List")
networktop.geometry("300x220")

Label(networktop, text="Nickname:").pack()
nickbox = Entry(networktop)
nickbox.grid(column="50", row="50")
nickbox.pack()

nick = nickbox.get()

Label(networktop, text="Alternate nick:").pack()
altbox = Entry(networktop)
altbox.grid(column="50", row="50")
altbox.pack()

altnick = altbox.get()

Label(networktop, text="Password:").pack()
pwbox = Entry(networktop, show="*")
pwbox.grid(column="50", row="50")
pwbox.pack()

password = pwbox.get()

Label(networktop, text="Channel to join:").pack()
chanbox = Entry(networktop)
chanbox.grid(column="50", row="50")
chanbox.pack()

channel = chanbox.get()

listvar = StringVar(networktop)
listvar.set("Choose a network...") # default value
listnetwork = OptionMenu(networktop, listvar, "irc.freenode.net")
listnetwork.config(width="50")
listnetwork.grid(column="50", row="50")
listnetwork.pack()

server = listvar.get()

networkconnect = Button(networktop, text="Connect", command=connect)
networkcancel = Button(networktop, text="Cancel", command=networktop.destroy)
networkcancel.pack(side=LEFT)
networkconnect.pack(side=RIGHT)

我在这里想要实现的是当输入某些内容时(例如“NickName”)它将顶部的nick =“”替换为nick =“NickName”,这样当按下“Connect”时它会连接使用“NickName”到服务器。但是我收到以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:\Users\dell\Desktop\irchat.py", line 29, in connect
    irc.connect((server, 6667))
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10049] The requested address is not valid in its context

我觉得我在这里是一个完全的菜鸟,解决方案可能很容易。的xD

1 个答案:

答案 0 :(得分:0)

在用户有机会输入任何文本之前,您似乎获得了条目窗口小部件的值。您正在创建窗口小部件,然后立即获取值。因此,server是空字符串,因此套接字代码失败。

在用户单击“连接”按钮之前,您不希望获得该值。