怎么用python 模拟鼠标实现鼠标绘图

tkinter是Python下面向tk的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter的优点是简单易用、与Python的结合度好。tkinter在Python 3.x下默认集成,不需要额外的安装操作;不足之处为缺少合适的可视化界面设计工具,需要通过代码来完成窗口设计和元素布局。
本节采用的Python版本为3.x,如果想在python 2.x下使用tkinter,请通过apt-get进行安装。需要注意的是,不同Python版本下的tkinter使用方式可能略有不同,建议采用Python3。
1.1.hello tkinter
首先介绍一个tkinter的基本例子,在IDLE中新建hello_tkinter.py,代码如下:
import tkinter as tk
# 建立tkinter窗口,设置窗口标题
top = tk.Tk()
top.title(&Hello Test&)
# 在窗口中创建标签
labelHello = tk.Label(top, text = &Hello Tkinter!&)
labelHello.pack()
# 运行并显示窗口
top.mainloop()
然后是top的概念和pack操作的说明:略&&(懒得写啦哈哈)
表1 Label组件常用参数
组件的高度(所占行数)
组件的宽度(所占字符个数)
前景字体颜色
多行文本的对齐方式,可选参数为: LEFT、 CENTER、RIGHT
文本左右两侧的空格数(默认为1)
文本上下两侧的空格数(默认为1)
在Shell下运行程序,就可以显示出一个简单的窗口了。
$ python3 hello_tkinter.py
Tkinter窗口效果
1.2.tkinter常用组件
虽然1.1中我们已经设计出了tkinter的基本窗口,但这时的窗口还过于简陋,除了显示信息以外无法实现任何有效的功能。为了完成更多的用户交互功能,我们还需要了解更多的tkinter界面元素,本节将介绍一些常用的tkinter组件。
1.2.1.按钮组件
按钮组件(Button)是tkinter最常用的图形组件之一,通过Button可以方便地与用户进行交互。下列代码实现了通过触发按钮事件(按下按钮)来执行指定操作(改变标签内容)的例子。
import tkinter as tk
def btnHelloClicked():
&&&&&&&&&&&&&&& labelHello.config(text = &Hello Tkinter!&)
top = tk.Tk()
top.title(&Button Test&)
labelHello = tk.Label(top, text = &Press the button...&, height = 5, width = 20, fg = &blue&)
labelHello.pack()
btn = tk.Button(top, text = &Hello&, command = btnHelloClicked)
btn.pack()
top.mainloop()
代码中定义了btnHelloClicked()函数,并通过给Button的command属性赋值来指定按钮按下时执行btnHelloClicked()函数中的代码的功能。在该函数中,通过labelHello.config()更改了label的text参数,即更改了标签的文字内容。
表2 Button组件基本参数
组件的高度(所占行数)
组件的宽度(所占字符个数)
前景字体颜色
activebackground
按钮按下时的背景颜色
activeforeground
按钮按下时的前景颜色
多行文本的对齐方式,可选参数为: LEFT、 CENTER、RIGHT
文本左右两侧的空格数(默认为1)
文本上下两侧的空格数(默认为1)
Button组件效果
1.2.2.输入框组件
输入框(Entry)用来输入单行内容,可以方便地向程序传递用户参数。这里通过一个转换摄氏度和华氏度的小程序来演示该组件的使用。
import tkinter as tk
def btnHelloClicked():
&&&&&&&&&&&&&&& cd = float(entryCd.get())
&&&&&&&&&&&&&&& labelHello.config(text = &%.2f&C = %.2f&F& %(cd, cd*1.8+32)) & & & &
&&&&&&&&&&&&&&&
top = tk.Tk()
top.title(&Entry Test&)
labelHello = tk.Label(top, text = &Convert &C to &F...&, height = 5, width = 20, fg = &blue&)
labelHello.pack()
entryCd = tk.Entry(top, text = &0&)
entryCd.pack()
btnCal = tk.Button(top, text = &Calculate&, command = btnHelloClicked)
btnCal.pack()
top.mainloop()
本例的代码从1.2.1中修改而来,并新建了一个Entry组件entryCd,text参数设置了输入框的默认值为&0&。当按钮按下后,通过entryCd.get()获取输入框中的文本内容,该内容为字符串类型,需要通过float()函数转换成数字,自后再进行换算并更新label显示内容。
表3 Entry组件常用参数
组件的高度(所占行数)
组件的宽度(所占字符个数)
前景字体颜色
将Entry框中的文本替换为指定字符,用于输入密码等,如设置 show=&*&
设置组件状态,默认为normal,可设置为:disabled&禁用组件,readonly&只读
华氏摄氏温度换算程序效果
1.2.3.单选、复选框
单选框(Radiobutton)和复选框(Checkbutton)分别用于实现选项的单选和复选功能。本例中的代码实现了通过单选框、复选框设置文字样式的功能。
import tkinter as tk
def colorChecked():
&&&&&&&&&&&&&&& labelHello.config(fg = color.get())
def typeChecked():
&&&&&&& textType = typeBlod.get() + typeItalic.get()
&&& &&&&if textType == 1:
&&&&&&&&&&&&&&& labelHello.config(font = (&Arial&, 12, &bold&))
&&&&&&& elif textType == 2:
&&&&&&&&&&&&&&& labelHello.config(font = (&Arial&, 12, &italic&))
&&&&&&& elif textType == 3:
&&&&&&&&&&&&&&& labelHello.config(font = (&Arial&, 12, &bold italic&))
&&&&&&& else :
&&&&&&&&&&&&&&& labelHello.config(font = (&Arial&, 12))
top = tk.Tk()
top.title(&Radio & Check Test&)
labelHello = tk.Label(top, text = &Check the format of text.&, height = 3, font=(&Arial&, 12))
labelHello.pack()
color = tk.StringVar()
tk.Radiobutton(top, text = &Red&, variable = color, value = &red&, command = colorChecked).pack(side = tk.LEFT)
tk.Radiobutton(top, text = &Blue&, variable = color, value = &blue&, command = colorChecked).pack(side = tk.LEFT)
tk.Radiobutton(top, text = &Green&, variable = color, value = &green&, command = colorChecked).pack(side = tk.LEFT)
typeBlod = tk.IntVar()
typeItalic = tk.IntVar()
tk.Checkbutton(top, text = &Blod&, variable = typeBlod, onvalue = 1, offvalue = 0, command = typeChecked).pack(side = tk.LEFT)
tk.Checkbutton(top, text = &Italic&, variable = typeItalic, onvalue = 2, offvalue = 0, command = typeChecked).pack(side = tk.LEFT)
top.mainloop()
在代码中,文字的颜色通过Radiobutton来选择,同一时间只能选择一个颜色。在三个Red、Blue和Green三个单选框中,定义了同样的变量参数color,选择不同的单选框会为该变量赋予不同的字符串值,内容即为对应的颜色。
任何单选框被选中都会触发colorChecked()函数,将标签修改为对应单选框表示的颜色。
表4&Radiobutton组件常用参数
单选框索引变量,通过变量的值确定哪个单选框被选中。一组单选框使用同一个索引变量
单选框选中时变量的值
单选框选中时执行的命令(函数)
文字的粗体、斜体样式则由复选框实现,分别定义了typeBlod和typeItalic变量来表示文字是否为粗体和斜体。
当某个复选框的状态改变时会触发typeChecked()函数。该函数负责判断当前那些复选框被选中,并将字体设置为对应的样式。
表5&Checkbutton组件常用参数
复选框索引变量,通过变量的值确定哪些复选框被选中。每个复选框使用不同的变量,使复选框之间相互独立
复选框选中(有效)时变量的值
复选框未选中(无效)时变量的值
复选框选中时执行的命令(函数)
1.2.4.绘图组件
绘图组件(Canvas)可以在GUI中实现2D图形的绘制,相当于画图板。组件内置了多种绘图函数,可以通过简单的2D坐标绘制直线、矩形、圆形、多边形等。本例代码演示了Canvas组件的绘图功能,更多的绘图函数可以查阅Canvas的参考页面。
import tkinter as tk
def drawCircle(self, x, y, r, **kwargs):
&&& return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
top = tk.Tk()
top.title(&Canvas Test&)
cvs = tk.Canvas(top, width = 600, height = 400)
cvs.pack()
cvs.create_line(50, 50, 50, 300)
cvs.create_line(100, 50, 200, 300, fill = &red&, dash = (4, 4), arrow = tk.LAST)
cvs.create_rectangle(200, 50, 400, 200, fill = &blue&)
cvs.create_oval(450, 50, 550, 200, fill = &green& )
drawCircle(cvs, 450, 300, 50, fill = &red&)
cvs.create_polygon(200, 250, 350, 250, 350, 350, 220, 300, fill=&yellow&)
top.mainloop()
绘图函数的参数都比较好理解,包括基本的坐标和颜色、线型等附加参数。
直线(line),即线段,通过两个端点定义。坐标顺序为x1、y1、x2、y2。
矩形(rectangle)通过对角线上的两个点来定义。
需要注意的是Canvas中没有画圆函数,这里通过绘制椭圆间接实现了绘制圆形的函数drawCircle()。椭圆(oval)是通过外切矩形的对角线两点来定义的(别告诉我你不知道什么是外切矩形&&)。如下图所示:
1.2.5.消息窗口
消息窗口(messagebox)用于弹出提示框向用户进行告警,或让用户选择下一步如何操作。消息框包括很多类型,常用的有info、warning、error、yeno、okcancel等,包含不同的图标、按钮以及弹出提示音。下面的代码演示了各消息框的运行效果,大家可以自己一一尝试。
import tkinter as tk
from tkinter import messagebox as msgbox
def btn1_clicked():
&&&&&&&&&&&&&&& msgbox.showinfo(&Info&, &Showinfo test.&)
def btn2_clicked():
&&&&&&&&&&&&&&& msgbox.showwarning(&Warning&, &Showwarning test.&)
def btn3_clicked():
&&&&&&&&&&&&&&& msgbox.showerror(&Error&, &Showerror test.&)& & & & & & & &
def btn4_clicked():
&&&&&&&&&&&&&&& msgbox.askquestion(&Question&, &Askquestion test.&)
def btn5_clicked():
&&&&&&&&&&&&&&& msgbox.askokcancel(&OkCancel&, &Askokcancel test.&)
def btn6_clicked():
&&&&&&&&&&&&&&& msgbox.askyesno(&YesNo&, &Askyesno test.&)& & & & & & & &
def btn7_clicked():
&&&&&&&&&&&&&&& msgbox.askretrycancel(&Retry&, &Askretrycancel test.&)
& & & & & & & &
top = tk.Tk()
top.title(&MsgBox Test&)
btn1 = tk.Button(top, text = &showinfo&, command = btn1_clicked)
btn1.pack(fill = tk.X)
btn2 = tk.Button(top, text = &showwarning&, command = btn2_clicked)
btn2.pack(fill = tk.X)
btn3 = tk.Button(top, text = &showerror&, command = btn3_clicked)
btn3.pack(fill = tk.X)
btn4 = tk.Button(top, text = &askquestion&, command = btn4_clicked)
btn4.pack(fill = tk.X)
btn5 = tk.Button(top, text = &askokcancel&, command = btn5_clicked)
btn5.pack(fill = tk.X)
btn6 = tk.Button(top, text = &askyesno&, command = btn6_clicked)
btn6.pack(fill = tk.X)
btn7 = tk.Button(top, text = &askretrycancel&, command = btn7_clicked)
btn7.pack(fill = tk.X)
top.mainloop()
旗下网站:
与非门科技(北京)有限公司 All Rights Reserved.
京ICP证:070212号
北京市公安局备案编号: 京ICP备:号[转载]Python模拟键盘输入和鼠标操作&
Python模拟键盘输入和鼠标操作
一、Python键盘输入模拟:
import win32api
import win32con
win32api.keybd_event(17,0,0,0) &#ctrl键位码是17
win32api.keybd_event(86,0,0,0) &#v键位码是86
win32api.keybd_event(86,0,win32con.KEYEVENTF_KEYUP,0) #释放按键
win32api.keybd_event(17,0,win32con.KEYEVENTF_KEYUP,0)
附个键位码表:
字母和数字键 & & 数字小键盘的键
& & & 功能键
&键 & 键码 &
& 键 & 键码 &
& & 键 & 键码
& & 0 & 96
&F1 & 112 &
& Backspace &
& & 1 & 97
&F2 & 113 &
& & 2 & 98
&F3 & 114 &
& Clear & &
& & 3 & 99
&F4 & 115 &
& Enter & &
& & 4 & 100
& 116 & & Shift
& & 5 & 101
Control & &
& & 6 & 102
& & 7 & 103
& 119 & & Caps
Lock & &20&
& & 8 & 104
& 120 & & Esc
& & 9 & 105
Spacebar &
& & * & 106
&122 & & Page Up
& & + & 107
&123 & & Page
Down & &34&
& & Enter 108 &
& & -- & --
& & - & 109
& Home & &
& & . & 110
&Left Arrow &
& & / & 111
&Up Arrow &
& & -- & --
&Right Arrow &
& & -- & --
&Down Arrow &
& & -- & --
&Insert & &
& & -- & --
&Delete & &
& & -- & --
& & -- & --
&Num Lock & &
& 其他未列出的字母和数字键盘为:ord(c)
二、&使用windll.user32实现鼠标模拟:
from ctypes import *
windll.user32.SetCursorPos(100, 100)
三. 使用AutoItX实现鼠标模拟:
#将AutoItX3.dll 文件复制到 window目录然后注册一下
regsvr32.exe AutoItX3.dll
from win32com.client import Dispatch
def enter_game():
&& & AutoItX
= Dispatch( "AutoItX3.Control" )
&& &# Block
&AutoItX.BlockInput( 1 )
&AutoItX.Sleep( 20000 )
AutoItX.WinActivate( GAME_WINDOW_TITLE, '' ):
& &if AutoItX.WinWaitActive(
GAME_WINDOW_TITLE, '', 8 ):
&# Unblock input
&AutoItX.BlockInput( 0 )
&return False
&AutoItX.WinSetTitle( GAME_WINDOW_TITLE, '',
_pre_title )
&AutoItX.WinSetState( _pre_title, '',
AutoItX.SW_MAXIMIZE )
&AutoItX.Sleep( 5000 )
&AutoItX.MouseMove( 462, 396, 10 )
&AutoItX.MouseClick( "left" )
&AutoItX.Sleep( 1000 )
&AutoItX.Send( GAME_ACCT_NAME )
&AutoItX.Sleep( 1000 )
&AutoItX.MouseMove ( 462, 472, 10 )
&AutoItX.MouseClick( "left" )
&AutoItX.Sleep( 1000 )
&AutoItX.Send( GAME_ACCT_PASS )
&AutoItX.Send( "{ENTER}" )
&AutoItX.Sleep( 10000 )
&& &# Unblock
&AutoItX.BlockInput( 0 )
&& &return
四. 使用跨平台的autopy实现
五、使用autohook监控键盘操作:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。将光标移到/点击文章中的句子上,可以查看原文。
显示译文 &&&&
显示原文 &&&&
如何在 python 中控制鼠标光标,换句话说,移动到特定位置并单击 Windows under?
17年05月05日
共12个回答
( pywin32-214.win32-py2.6.exe在我的示例中) 之后在 python 2.6上测试:
import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)
70年01月01日
你可以使用 win32api 或者 ctypes 模块来使用 win32 api来控制鼠标或者任何 gui
下面是一个有趣的示例,它使用切入点来控制鼠标:
import win32api
import time
import math
for i in range(500):
x = int(500+math.sin(math.pi*i/100)*500)
y = int(500+math.cos(i)*100)
win32api.SetCursorPos((x,y))
time.sleep(.01)
点击使用 ctypes:
import ctypes
# see /en-us/library/ms646260(VS.85).aspx for details
ctypes.windll.user32.SetCursorPos(100, 20)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
70年01月01日
查看跨平台 PyMouse:
70年01月01日
另一个选项是使用 cross-platform
。 这里软件包有两种不同的移动鼠标选项:
这里代码段将立即将光标移动到位置( 200,200 ):
import autopy
autopy.mouse.move(200,200)
如果你想让光标在屏幕上明显移动到指定位置,可以使用smooth_move命令:
import autopy
autopy.mouse.smooth_move(200,200)
70年01月01日
不知道 python,但也许谷歌会帮助你
"python 控制鼠标移动"显示
from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
70年01月01日
PyAutoGUI模块执行这里操作并在 win/mac/linux.
import pyautogui
pyautogui.click(100, 100)
还有其他功能:
import pyautogui
pyautogui.moveTo(100, 150)
pyautogui.moveRel(0, 10) # move mouse 10 pixels down
pyautogui.dragTo(100, 150)
pyautogui.dragRel(0, 10) # drag mouse 10 pixels down
这比浏览所有的win32con内容要容易得多。
70年01月01日
库在 Windows 7上单击任意 clicks 时间的快速和dirty函数。 不需要下载。
import ctypes
SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event
def left_click(x, y, clicks=1):
SetCursorPos(x, y)
for i in xrange(clicks):
mouse_event(2, 0, 0, 0, 0)
mouse_event(4, 0, 0, 0, 0)
left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.
70年01月01日
Copyright (C) 2011 HelpLib All rights reserved. &&在数据分析的过程中,往往需要对所建立的模型进行可视化,并调整其中的某些参数。
通常情况下,在Python中可以通过Matplotlib来进行绘制图像。然而该绘制过程是静态的,也就是每次调整完参数需要重新调用绘图语句进行绘图展示。我们的目标是结合GUI组件,实现对模型参数的交互式绘图。这样,可以在展示出的GUI界面中动态的调整模型的参数,并绘制图像。
最终实现的效果如下:
可以通过GUI界面指定参数绘制散点图。
该过程需要结合Python的Tkinter库来进行GUI部分的实现。代码如下:
1: #!/usr/bin/env python
2: #coding:utf-8
Chaos --&&
Purpose: 修改Matplotlib的后端,实现在Tkinter的GUI绘制图像
8: import numpy as np
9: from Tkinter import *
10: import matplotlib
11: from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
12: from matplotlib.figure import Figure
14: #----------------------------------------------------------------------
15: def drawPic():
获取GUI界面设置的参数,利用该参数绘制图片
#获取GUI界面上的参数
try:sampleCount=int(inputEntry.get())
sampleCount=50
print '请输入整数'
inputEntry.delete(0,END)
inputEntry.insert(0,'50')
#清空图像,以使得前后两次绘制的图像不会重叠
drawPic.f.clf()
drawPic.a=drawPic.f.add_subplot(111)
#在[0,100]范围内随机生成sampleCount个数据点
x=np.random.randint(0,100,size=sampleCount)
y=np.random.randint(0,100,size=sampleCount)
color=['b','r','y','g']
#绘制这些随机点的散点图,颜色随机选取
drawPic.a.scatter(x,y,s=3,color=color[np.random.randint(len(color))])
drawPic.a.set_title('Demo: Draw N Random Dot')
drawPic.canvas.show()
43: if __name__ == '__main__':
matplotlib.use('TkAgg')
#在Tk的GUI上放置一个画布,并用.grid()来调整布局
drawPic.f = Figure(figsize=(5,4), dpi=100)
drawPic.canvas = FigureCanvasTkAgg(drawPic.f, master=root)
drawPic.canvas.show()
drawPic.canvas.get_tk_widget().grid(row=0, columnspan=3)
#放置标签、文本框和按钮等部件,并设置文本框的默认值和按钮的事件函数
Label(root,text='请输入样本数量:').grid(row=1,column=0)
inputEntry=Entry(root)
inputEntry.grid(row=1,column=1)
inputEntry.insert(0,'50')
Button(root,text='画图',command=drawPic).grid(row=1,column=2,columnspan=3)
#启动事件循环
root.mainloop()
阅读(...) 评论()}

我要回帖

更多关于 python实现鼠标点击 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信