我是真的没分了 请帮帮忙 。。。

water_tian 2007-08-16 12:51:11
在PYTHON 2.1 宝典 上的一个例子 可是我不知道如何运行它
请问是用IDLE 运行吗 ? 麻烦写个运行过程

from Tkinter import *
from socket import *
import cPickle, threading, sys

# Each message is a command + data
CMD_JOINED,CMD_LEFT,CMD_MSG,CMD_LINE,CMD_JOINRESP = range(5)
people = {}# key = (ipaddr,port),value = (name,color)

def sendMsg(msg):
sendSock.send(msg,0)

def onQuit():
'User clicked Quit button'
sendMsg(chr(CMD_LEFT)) # Notify others that I'm leaving
root.quit()

def onMove(e):
'Called when LButton is down and mouse moves'
global lastLine,mx,my
canvas.delete(lastLine) # Erase temp line
mx,my = e.x,e.y

# Draw a new temp line
lastLine = canvas.create_line(dx,dy,mx,my,width=2,fill='Black')

def onBDown(e):
'User pressed left mouse button'
global lastLine,dx,dy,mx,my
canvas.bind('<Motion>',onMove) # Start receiving move msgs
dx,dy = e.x,e.y
mx,my = e.x,e.y

# Draw a temporary line
lastLine = canvas.create_line(dx,dy,mx,my,width=2,fill='Black')

def onBUp(e):
'User released left mouse button'
canvas.delete(lastLine) # Erase the temporary line
canvas.unbind('<Motion>') # No more move msgs, please!

# Send out the draw-a-line command
sendMsg(chr(CMD_LINE)+cPickle.dumps((dx,dy,e.x,e.y),1))

def onEnter(foo):
'User hit the [Enter] key'
sendMsg(chr(CMD_MSG)+entry.get())
entry.delete(0,END) # Clear the entry widget

def setup(root):
'Creates the user interface'
global msgs,entry,canvas

# The big window holding everybody's messages
msgs = Text(root,width=60,height=20)
msgs.grid(row=0,col=0,columnspan=3)

# Hook up a scrollbar to see old messages
s = Scrollbar(root,orient=VERTICAL)
s.config(command=msgs.yview)
msgs.config(yscrollcommand=s.set)
s.grid(row=0,col=3,sticky=N+S)

# Where you type your message
entry = Entry(root)
entry.grid(row=1,col=0,columnspan=2,sticky=W+E)
entry.bind('<Return>',onEnter)
entry.focus_set()

b = Button(root,text='Quit',command=onQuit)
b.grid(row=1,col=2)

# A place to draw
canvas = Canvas(root,bg='White')
canvas.grid(row=0,col=5)

# Notify me of button press and release messages
canvas.bind('<ButtonPress-1>',onBDown)
canvas.bind('<ButtonRelease-1>',onBUp)

def msgThread(addr,port,name):
'Listens for and processes messages'

# Create a listen socket
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
s.bind(('',port))

# Join the multicast group
s.setsockopt(SOL_IP,IP_ADD_MEMBERSHIP,inet_aton(addr)+inet_aton(''))

while 1:
# Get a msg and strip off the command byte
msg,msgFrom = s.recvfrom(2048)
cmd,msg = ord(msg[0]),msg[1:]

if cmd == CMD_JOINED: # New join
msgs.insert(END,'(%s joined the chat)\n' % msg)

# Introduce myself
sendMsg(chr(CMD_JOINRESP)+ cPickle.dumps((name,myColor),1))

elif cmd == CMD_LEFT: # Somebody left
who = people[msgFrom][0]
if who == name: # Hey, _I_ left, better quit
break
msgs.insert(END,'(%s left the chat)\n' % who,'color_'+who)

elif cmd == CMD_MSG: # New message to display
who = people[msgFrom][0]
msgs.insert(END,who,'color_%s' % who)
msgs.insert(END,': %s\n' % msg)

elif cmd == CMD_LINE: # Draw a line
dx,dy,ex,ey = cPickle.loads(msg)
canvas.create_line(dx,dy,ex,ey,width=2, fill=people[msgFrom][1])

elif cmd == CMD_JOINRESP: # Introducing themselves
people[msgFrom] = cPickle.loads(msg)
who,color = people[msgFrom]

# Create a tag to draw text in their color
msgs.tag_configure('color_' + who,foreground=color)

# Leave the multicast group
s.setsockopt(SOL_IP,IP_DROP_MEMBERSHIP, inet_aton(addr)+inet_aton(''))

if __name__ == '__main__':
argv = sys.argv
if len(argv) < 3:
print 'Usage:',argv[0],'<name> <color>' '[addr=<multicast address>] [port=<port>]'
sys.exit(1)

global name, addr, port, myColor
addr = '235.0.50.5' # Default IP address
port = 54321 # Default port
name,myColor = argv[1:3]
for arg in argv[3:]:
if arg.startswith('addr='):
addr = arg[len('addr='):]
elif arg.startswith('port='):
port = int(arg[len('port='):])

# Start up a thread to process messages
threading.Thread(target=msgThread, args=(addr,port,name)).start()

# This is the socket over which we send out messages
global sendSock
sendSock = socket(AF_INET,SOCK_DGRAM)
sendSock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
sendSock.connect((addr,port))

# Don't let the packets die too soon
sendSock.setsockopt(SOL_IP,IP_MULTICAST_TTL,2)

# Create a Tk window and create the GUI
root = Tk()
root.title('%s chatting on channel %s:%d' % (name,addr,port))
setup(root)

# Join the chat!
sendMsg(chr(CMD_JOINED)+name)
root.mainloop()



...全文
212 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
water_tian 2007-08-16
  • 打赏
  • 举报
回复
那书上就是大概说了个原理 。。。 有个图片都看不清 电子书 。。。 比较恶心

没想到 例题还有错误
water_tian 2007-08-16
  • 打赏
  • 举报
回复
没有示范 我加入参数了啊
Traceback (most recent call last):
File "char.py", line 158, in <module>
setup(root)
File "char.py", line 55, in setup
msgs.grid(row=0,col=0,columnspan=3)
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1859, in grid_configure
+ self._options(cnf, kw))
_tkinter.TclError: ambiguous option "-col": must be -column, -columnspan, -in, -
ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky

这些是错误提示啊
iambic 2007-08-16
  • 打赏
  • 举报
回复
不要用IDLE执行,从命令行中执行。因为这个程序需要命令行参数。

参数的使用书中有没有示范?
water_tian 2007-08-16
  • 打赏
  • 举报
回复
我设置了环境变量 。。。
可是 哎 ,,,,,,,,,
例题有错误 太恶心了 。。。。。。。。。
Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.

C:\Documents and Settings\Administrator>cd ..

C:\Documents and Settings>cd ..

C:\>python char.py water SlateBlue4
Traceback (most recent call last):
File "char.py", line 158, in <module>
setup(root)
File "char.py", line 55, in setup
msgs.grid(row=0,col=0,columnspan=3)
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1859, in grid_configure
+ self._options(cnf, kw))
_tkinter.TclError: ambiguous option "-col": must be -column, -columnspan, -in, -
ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky
wuyu637 2007-08-16
  • 打赏
  • 举报
回复
提示不是可执行命令,也不是可执行程序或批处理文件,是因为你的电脑的环境变量里没有加上
python的路径。

有IDLE的话可以用下面两种方式执行:
第一个是在编辑窗口,菜单栏有一个 run, ---> run model (快捷方式f5)
第二个是在python shell 下输入 .py的路径 +.py文件名执行。


water_tian 2007-08-16
  • 打赏
  • 举报
回复
大哥 我好像见过你哦 ~~~

当我输入的时候 提示 ‘python’不是内部或外部命令,也不是可执行程序或批处理文件。
iambic 2007-08-16
  • 打赏
  • 举报
回复
这个程序需要接受运行参数的,你需要启动一个cmd窗口:

开始菜单->运行->cmd

从窗口中进入你的代码所在目录,比如你把代码保存为D:\projects\python\main.py

那么在cmd窗口中依次键入:

D:
cd projects
cd python

然后运行你的脚本:

python main.py 其他参数

这个“其它参数”需要参考你用的书。书上应该讲清除了怎样使用这个脚本。

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧