python - Tkinter:为用户选择的点设置颜色

标签 python tkinter

我有一个图像保存为image.png。我的任务的工作流程是这样的:

  1. 在 Tkinter 中加载图像以及图像下方的“选择两点”按钮
  2. 用户在图像的两个点上单击鼠标左键两次
  3. 当他选择第一个点时,该特定点会突出显示(例如以红色或任何颜色);然后他选择第二个点,第二个点也会突出显示
  4. 两点的(x,y)坐标存储在全局变量中,稍后会用到
  5. 一旦用户选择了两个点,就会出现第二个“完成!”按钮出现。单击此按钮后,GUI 将关闭。 N.B 我希望这两点保持突出显示,直到用户单击关闭按钮,以便他/她知道他/她单击的位置

我设法解决了除第 3 步之外的所有步骤。我发现的最相似的事情是使用canvas.create_rectangle(x,y,x+1,y+1,fill="red")创建一个矩形,但首先我更喜欢一个圆形其次,我无法将 canvas 链接到我的 Label

任何帮助将不胜感激:D

这是到目前为止我的代码:

root = Tk()  # create a window

frame = Frame(root)  # define upper frame
middleframe = Frame(root)  # define middle frame
exitFrame = Frame(root)  # define exit frame
frame.pack()  # pack the frame
middleframe.pack()  # pack the subframe
exitFrame.pack(side = 'bottom')  # pack the exit frame

# function that closes the GUI
def close_window(): 
    root.destroy()

# load the image
img = PhotoImage(file="image.png")  # save the image
panel = Label(frame, image=img)  # display the image as a label
panel.grid(row=0, column=0)  # pack the image

# make the user select some points
global x_Coordinates  # initialize empty list for storing x-axis coordinates
global y_Coordinates  # initialize empty list for storing y-axis coordinates
x_Coordinates = []
y_Coordinates = []

clicks = 0
def countClicks():
  global clicks # this will use the variable to count
  clicks = clicks + 1  # increment "clicks"
  if clicks == 2: # if the user has selected 2 points, add a button that closes the window
      exit_button = Button(exitFrame, state = "normal", text = "Done!", command = close_window)  # link the closing function to the button
      exit_button.grid(row=2, column=0, pady=5)  # set button position with "grid"        
pass

def selectPoints():  # function called when user clicks the button "select two points"
    panel.bind("<Button 1>", saveCoordinates)  #  link the function to the left-mouse-click event
    exit_button = Button (exitFrame, state = "disabled", text = "Done!", command = close_window)  # link closing function to the button
    exit_button.grid(row=2, column=0, pady=5)  # set button position with "grid"
    button_select_points.config(state = "disabled") # switch button state to "disabled"

def saveCoordinates(event): # function called when left-mouse-button is clicked   
    x_coordinate = event.x  # save x and y coordinates selected by the user
    y_coordinate = event.y
    x_Coordinates.append(x_coordinate)  # append to external list
    y_Coordinates.append(y_coordinate)  # append to external list
    countClicks()  # invoke function "countClicks"

button_select_points = Button(middleframe, text = "select two points", command = selectPoints)  # insert button and link it to "selectPoints"
button_select_points.grid(row=1, column=0, pady=5)  # set button position with "grid"

root.mainloop()  # keep the GUI open

最佳答案

除非您想要做的不仅仅是设置几个像素,否则使用 Canvas 可能会更容易小部件,它具有一些更高级别的绘图基元(例如矩形和椭圆形)。

(这里有一些关于 Canvas 小部件的相当全面的 Tkinter 文档。)

下面是您的代码,经过修改以执行此操作(加上其他一些代码,通过遵循 PEP 8 - Style Guide for Python Code 指南并删除一些我认为不必要和/或过于多余的内容,使其更具可读性)。

它定义了一个名为 create_circle() 的新辅助函数简化调用更通用Canvas小部件的create_oval()方法。现在,这在您的 saveCoordinates() 中被调用。函数(现在绑定(bind)到新 "<Button 1>" 对象的 Canvas 事件,而不是您正在使用的 Label )。

from tkinter import *

root = Tk()  # create a window

frame = Frame(root)  # define upper frame
middleframe = Frame(root)  # define middle frame
exitFrame = Frame(root)  # define exit frame
frame.pack()  # pack the frame
middleframe.pack()  # pack the subframe
exitFrame.pack(side='bottom')  # pack the exit frame

# function that closes the GUI
def close_window():
    root.destroy()

img = PhotoImage(file="myimage.png")  # load the image
canvas = Canvas(frame, width=img.width(), height=img.height(), borderwidth=0)
canvas.grid(row=0, column=0)
canvas.create_image(0, 0, image=img, anchor=NW)

# make the user select some points
x_Coordinates = []  # list for storing x-axis coordinates
y_Coordinates = []  # list for storing y-axis coordinates
clicks = 0

def create_circle(canvas, x, y, radius, **kwargs):
    return canvas.create_oval(x-radius, y-radius, x+radius, y+radius, **kwargs)

def countClicks():
    global clicks

    clicks += 1
    # if the user has selected 2 points, add a button that closes the window
    if clicks == 2:
        # link the closing function to the button
        exit_button = Button(exitFrame, state="normal", text="Done!",
                             command=close_window)
        exit_button.grid(row=2, column=0, pady=5)  # set button position with "grid"

def selectPoints():  # function called when user clicks the button "select two points"
    # link the function to the left-mouse-click event
    canvas.bind("<Button 1>", saveCoordinates)
    # link closing function to the button
    exit_button = Button (exitFrame, state="disabled", text="Done!",
                          command=close_window)
    exit_button.grid(row=2, column=0, pady=5)  # set button position with "grid"
    button_select_points.config(state="disabled") # switch button state to "disabled"

def saveCoordinates(event): # function called when left-mouse-button is clicked
    x_coordinate = event.x  # save x and y coordinates selected by the user
    y_coordinate = event.y
    x_Coordinates.append(x_coordinate)
    y_Coordinates.append(y_coordinate)
    # Display a small dot showing position of point.
    create_circle(canvas, x_coordinate, y_coordinate, radius=3, fill='red')
    countClicks()

# insert button and link it to "selectPoints"
button_select_points = Button(middleframe, text="select two points",
                              command=selectPoints)
button_select_points.grid(row=1, column=0, pady=5)

root.mainloop()  # keep the GUI open

关于python - Tkinter:为用户选择的点设置颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53211845/

相关文章:

python - 一次只允许用户选择一个复选按钮?

python - 将多个 if 和 elif 语句应用于 for 循环中字符串列表中的子字符串

Python/django 日志记录权限错误

python - 使用 xadmin 时出错

python - 如何根据每组的条件屏蔽列中的值

python - 窗口加载时如何默认将光标放在 Entry 小部件上?

python - 有没有办法将数据框从 Python 返回到 R ?

python - 如何设置tkinter框架的透明度?

python - AttributeError: 'MyReturnWindow' 对象没有属性 'selected_index'

python-3.x - 我可以获得第二次单击鼠标时的函数(不在当前窗口上)