所以今天我一直在使用tkinter开发一个新的GUI,然后遇到了将一个字符串从一个字符串解析为一个int的问题,我得到了这个错误。
Traceback (most recent call last):
File "/Users/g.shiner21/Desktop/Python/P2PFile/P2PFileServer.py", line 47, in <module>
bStartServer = Button(f1, text="Start Server", command=startServer(host))
File "/Users/g.shiner21/Desktop/Python/P2PFile/P2PFileServer.py", line 28, in startServer
intport = int(port)
ValueError: invalid literal for int() with base 10: ''
这是函数,
def startServer(host):
port = ePort.get()
intport = int(port)
s = socket.socket()
s.bind((host, intport))
s.listen(4)
最令人困惑的部分是,当我测试这样的东西时,
strTest = "10000"
intTest = int(strTest)
我没有错误。所以我不认为我的解析错了。但在这一点上,我不太确定。任何帮助将不胜感激! :)
编辑:对于那些有帮助的人来说这是完整的程序(或者至少我到目前为止。我在构建GUI时注释掉了它的第二部分因为我不想要处理任何干扰。
# server.py
import socket # Import socket module
import sys
from tkinter import *
from tkinter import ttk
port = 0 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = "0.0.0.0"
root=Tk()
root.title("Test Window")
c = '#ececec'
n = ttk.Notebook(root) #Create notebook
f1 = ttk.Frame(n) #Create frames for notebook
f2 = ttk.Frame(n)
f3 = ttk.Frame(n)
n.add(f1, text='Server') #Add frames to notebook
n.add(f2, text='File')
n.add(f3, text='Playback')
n.pack(expand=1, fill='both') #Pack notebook
def startServer(host):
port = ePort.get()
intport = int(port)
s = socket.socket()
s.bind((host, intport))
s.listen(4)
lservType = Label(f1, text="Select Server Type: ", bg=c)
lservType.grid(columnspan=2, row=0)
R1 = Radiobutton(f1, text="Local Host", variable=host, value="localhost", bg=c)
R1.grid(row=1, column=0)
R2 = Radiobutton(f1, text="Wireless Host", variable=host, value="0.0.0.0", bg=c)
R2.grid(row=1, column=1)
lPort = Label(f1, text="Port: ", bg=c)
ePort = Entry(f1)
lPort.grid(row=2, column=0, sticky='e')
ePort.grid(row=2, column=1)
bStartServer = Button(f1, text="Start Server", command=startServer(host))
bStartServer.grid(row=3, columnspan=2)
"""
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = "0.0.0.0" # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(4) # Now wait for client connection.
#print("Your IP address is: " + socket.gethostbyname(socket.gethostname()))
print ('Server listening....')
while True:
conn, addr = s.accept() # Establish connection with client.
` print ('Got connection from', addr)
input ('Press the enter key to send')
filename = 'send.mov'
print ('File Assigned')
f = open(filename,'rb')
print ('File Oppened')
l = f.read(131072)
print ('Reading')
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(131072)
print ('Reading')
f.close()
print('Done sending')
conn.close()
#sys.exit()
"""
root.mainloop()
答案 0 :(得分:1)
当python无法将变量强制转换为int时,会出现此错误。确保&#34; port&#34;是一个整数,并尝试转换为int。第二个例子工作正常,因为你硬编码输入的值,它是一个整数。您可以按如下方式更新您的功能:
def startServer(host):
try:
port = ePort.get()
intport = int(port)
s = socket.socket()
s.bind((host, intport))
s.listen(4)
except BaseException:
print('wrong entry')