Tkinter数据不打印

时间:2018-06-07 23:56:58

标签: python python-2.x tk tkinter-canvas

我正在处理任务,我正在向用户显示图像。用户将单击图像上的任意位置,将打印坐标。

Tkinter库canvas用于向用户显示图像,允许用户点击图像上的任何位置。

printcoords()功能有什么问题 - 为什么它没有显示任何内容?

这是代码。

from Tkinter import *
import ImageTk
from PIL import Image, ImageDraw
from Tkinter import Tk, Menu, Canvas


if __name__ == '__main__':


        #function on mouse click
    def printcoords(event):
            print "tahir"
            #outputting x and y coords to console
            data.append([event.x,event.y])
            print data
    #mouseclick event 

    root = Tk() 
    img = Image.open("eurecat1.png")
         # Draw grid

    step_count = 50
    draw = ImageDraw.Draw(img)
    y_start = 0
    y_end = img.height
    step_size = int(img.width / step_count)

    for x in range(0, img.width, step_size):
        line = ((x, y_start), (x, y_end))
        draw.rectangle(line, fill="black")

    x_start = 0
    x_end = img.width

    for y in range(0, img.height, step_size):
        line = ((x_start, y), (x_end, y))
        draw.rectangle(((x_start,y), (x_end, y)), fill="black")





   # loadImage(canvas, img)

    filename = ImageTk.PhotoImage(img)
    canvas = Canvas(root,height=img.size[0],width=img.size[0])
    canvas.image = filename  # <--- keep reference of your image
    canvas.create_image(0,0,anchor='nw',image=filename)
    canvas.pack()


    canvas.config(scrollregion=canvas.bbox(ALL))

    frame = Frame(root, bd=2, relief=SUNKEN)
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    xscroll = Scrollbar(frame, orient=HORIZONTAL)
    xscroll.grid(row=1, column=0, sticky=E+W)
    yscroll = Scrollbar(frame)
    yscroll.grid(row=0, column=1, sticky=N+S)
    canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
    canvas.grid(row=0, column=0, sticky=N+S+E+W)
    xscroll.config(command=canvas.xview)
    yscroll.config(command=canvas.yview)
    frame.pack(fill=BOTH,expand=1)  


    data=[]     

#function on mouse click
    def printcoords(event):
            print "tahir"
            #outputting x and y coords to console
            data.append([event.x,event.y])
            print data
    #mouseclick event



    canvas.bind("<Button 1>", printcoords)

    root.mainloop()

1 个答案:

答案 0 :(得分:0)

正如@abamert所提到的,你有两个具有相同名称的函数,你发布的代码具有不必要的复杂性,对解决问题没有用。

以下是一个可用于修复代码的最小示例:

import Tkinter as tk


def printcoords(event):
    print event.x, event.y


if __name__ == '__main__':

    root = tk.Tk()
    canvas = tk.Canvas(root)
    canvas.pack()
    canvas.bind("<Button 1>", printcoords)

    root.mainloop()