如何点击鼠标在特定点做某事?

时间:2016-11-21 20:44:12

标签: python zelle-graphics

如果鼠标点击Zelle图形中的某个点,我怎么能让它做点什么?我想要做的是当我点击"开始按钮"图片。但是,我显然做错了,因为我的程序崩溃或者什么都不做。

from graphics import *
import time
#from tkinter import *

win = GraphWin('Stopwatch', 600, 600)
win.yUp()

#Assigning images
stopWatchImage = Image(Point (300, 300), "stopwatch.png")
startImage = Image(Point (210, 170), "startbutton.png")
stopImage = Image(Point (390, 170), "stopbutton.png")
lapImage = Image(Point (300, 110), "lapbutton.png")


stopWatchImage.draw(win)
startImage.draw(win)
stopImage.draw(win)
lapImage.draw(win)


sec = 0
minute = 0
hour = 0

def isBetween(x, end1, end2):
'''Return True if x is between the ends or equal to either.
The ends do not need to be in increasing order.'''

    return end1 <= x <= end2 or end2 <= x <= end1

def isInside(point, startImage):
'''Return True if the point is inside the Rectangle rect.'''

    pt1 = startImage.getP1()
    pt2 = startImage.getP2()
    return isBetween(point.getX(), pt1.getX(), pt2.getX()) and \
           isBetween(point.getY(), pt1.getY(), pt2.getY())


def getChoice(win):     #NEW
'''Given a list choicePairs of tuples with each tuple in the form
(rectangle, choice), return the choice that goes with the rectangle
in win where the mouse gets clicked, or return default if the click
is in none of the rectangles.'''

    point = win.getMouse()
    if isInside(point, startImage):
        time.sleep(1)
        sec += 1
        timeText.setText(sec)
        timeText.setText('')


        while sec >= 0 and sec < 61:

         #Displaying Time
            timeText = Text(Point (300,260), str(hour) + ":" + str(minute) + ":" + str(sec))
            timeText.setSize(30)
            timeText.draw(win)
            time.sleep(1)
            sec += 1
            timeText.setText(sec)
            timeText.setText('')
            #Incrementing minutes,hours
            if sec == 60:
                sec = 0        
                minute += 1

            if minute == 60:
                sec = 0
                minute = 0
                hour += 1


return default


def layout()
    getChoice(win)

layout()

我似乎无法让它发挥作用。

编辑:添加了我的其余代码以供澄清。

1 个答案:

答案 0 :(得分:0)

您可以使用setMouseHandler指定在单击窗口时调用的函数。

在示例中,如果单击窗口的左侧部分然后绘制矩形,如果单击窗口的右侧部分,则绘制圆形。

您可以打开文件graphics.py并查看所有代码。这是最快的方法,可以看到你可以使用的功能。

from graphics import *

# --- functions ---

def on_click(point):
    # inform function to use global variable
    global win

    if point.x > win.width//2:
        c = Circle(point, 10)
        c.draw(win)
    else:
        a = Point(point.x - 10, point.y - 10)
        b = Point(point.x + 10, point.y + 10)
        r = Rectangle(a, b)
        r.draw(win)

def main():
    # inform function to use global variable
    global win

    win = GraphWin("My Circle", 500, 500)

    win.setMouseHandler(on_click)

    win.getKey() 
    win.close()

# --- start ---

# create global variable
win = None

main()

BTW: graphics使用Tkinter,其中包含小工具ButtonLabelText等。它可以使用{ {1}}将小部件添加到画布。

canvas.create_window()还有函数Tkinter,它允许您定期执行函数 - 即。更新时间。

示例

after(miliseconds, function_name)

Tkinter:CanvasButtonother

编辑:工作示例

from graphics import *
import datetime

# --- classes ---

class _Widget():
    def __init__(self, x, y, w, h, **options):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.options = options

    def draw(self, canvas, **options):
        return None

    def set(self, **options):
        self.widget.config(options)

    def get(self, **options):
        self.widget.cget(options)

class Button(_Widget):

    def draw(self, canvas, **options):
        x, y = canvas.toScreen(self.x, self.y) # ???

        self.widget = tk.Button(canvas, self.options)

        return canvas.create_window((x, y), options, width=self.w, height=self.h, window=self.widget, anchor='nw')

class Label(_Widget):

    def draw(self, canvas, **options):
        x, y = canvas.toScreen(self.x, self.y) # ???

        self.widget = tk.Label(canvas, self.options)

        return canvas.create_window((x, y), options, width=self.w, height=self.h, window=self.widget, anchor='nw')

# --- functions ---

def on_start():
    #global b1, b2
    global running

    b1.set(state='disabled')
    b2.set(state='normal')

    running = True

    # run first time
    update_time()

    print("START")

def on_stop():
    #global b1, b2
    global running

    b1.set(state='normal')
    b2.set(state='disabled')
    l.set(text="Controls:")

    running = False

    print("STOP")

def update_time():
    #global l
    #global running

    if running:

        l.set(text=datetime.datetime.now().strftime("%H:%M:%S"))

        # run again after 1000ms (1s)
        win.after(1000, update_time)

# --- main ---

def main():
    global win, l, b1, b2

    win = GraphWin("My Buttons", 500, 500)

    l = Label(0, 0, 100, 50, text="Controls:")
    l.draw(win)

    b1 = Button(100, 0, 100, 50, text="START", command=on_start)
    b1.draw(win)

    b2 = Button(200, 0, 100, 50, text="STOP", command=on_stop, state='disabled')
    b2.draw(win)

    win.getKey() 
    win.close()

# --- global variable to access in functions ---

win = None
l  = None
b1 = None
b2 = None

running = False

# --- start ---

main()