1

在 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()

我似乎无法让它工作。

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

4

1 回答 1

1

您可以使用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()

顺便说一句: graphics使用Tkinter具有小部件Button,,LabelText。它可以canvas.create_window()用来将小部件添加到画布。

Tkinter还具有after(miliseconds, function_name)可让您定期执行功能的功能-即。更新时间。

例子

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()

Tkinter:画布按钮其他


编辑: 工作示例

from graphics import *


def isBetween(x, end1, end2):
    return end1 <= x <= end2 or end2 <= x <= end1

def isInside(point, startImage):
    x = startImage.getAnchor().getX()
    y = startImage.getAnchor().getY()
    w = startImage.getWidth()/2
    h = startImage.getHeight()/2

    pt1_x = x - w
    pt1_y = y - h

    pt2_x = x + w
    pt2_y = y + h

    return isBetween(point.getX(), pt1_x, pt2_x) and \
           isBetween(point.getY(), pt1_y, pt2_y)


def getChoice(event):
    global hour, minute, sec
    global running

    point = Point(round(event.x), round(event.y))

    if isInside(point, startImage):
        sec = 0
        minute = 0
        hour = 0
        running = True
        update_time()

    if isInside(point, stopImage):
        running = False


def update_time():
    global hour, minute, sec
    #global timeText
    #global win

    sec += 1

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

    timeText.setText('{}:{}:{}'.format(hour, minute, sec))

    if running:
        win.after(1000, update_time)
    else:
        timeText.setText('')


def layout():
    global win
    global stopWatchImage
    global startImage
    global stopImage
    global lapImage
    global timeText

    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")

    #Drawing images
    stopWatchImage.draw(win)
    startImage.draw(win)
    stopImage.draw(win)
    lapImage.draw(win)

    timeText = Text(Point(300,260), '')
    timeText.setSize(30)
    timeText.draw(win)

    win.setMouseHandler(getChoice)

    win.getKey()

# --- global variable ---

win = None

stopWatchImage = None
startImage = None
stopImage = None
lapImage = None

timeText = None

running = False

# --- start ---

layout()
于 2016-11-21T21:16:35.253 回答