如何在python中使用Tkinter库获取简单的绘图应用程序以在屏幕上显示结果?

问题描述 投票:0回答:1
 from tkinter import *
import tkinter as tk

class Paint():
    def __init__(self):

        self.window=Tk()
        self.sizex=500
        self.sizey=500


        self.canvas = Canvas(self.window, width=self.sizex, height=self.sizey, bg="white")
        self.canvas.pack()
        self.img = PhotoImage(width=self.sizex, height=self.sizey)
        self.canvas.create_image((self.sizex, self.sizey), image=self.img, state="normal")
        self.canvas.bind("<Button-1>",self.color_in)

    def color_in(self, event):
        self.img.put("black", (event.x, event.y))
paint=Paint()
mainloop()

在上面的代码中,我可以打开一个空白的白色窗口,但是当我点击屏幕上的任何位置时,没有任何变化。如何让窗口更新?

python tkinter pixel
1个回答
0
投票

几件事:

您应该只导入一次Tkinter。如果您将其导入为“tk”,您的代码将更容易理解。

如果为不同的小部件设置不同的颜色,则很容易看出它们是否在您希望的位置。

将图像放在画布上时,将其放在右下角的500,500位置。默认锚点位于图像的中心。这导致你只看到图像的左上角1/4,正如布莱恩指出的那样。

我已将图像重新定位到(0,0)并将左上角('nw')指定为锚点。此外,帆布highlightthickness=0从画布中删除2像素高光边框。图像state='normal'是默认值。

最后,我将图像上的标记放大了一点,以便于查看。我调整了对mainloop()的调用

图像自动更新,现在它处于正确的位置。

import tkinter as tk

class Paint():
    def __init__(self):
        self.window = tk.Tk()
        self.sizex = 500
        self.sizey = 500
        self.canvas = tk.Canvas(self.window, width=self.sizex,
                             height=self.sizey, highlightthickness=0)
        # Set canvas background color so you can see it
        self.canvas.config(bg="thistle")
        self.canvas.pack()

        self.img = tk.PhotoImage(width=self.sizex, height=self.sizey)
        self.canvas.create_image((0,0), image=self.img, state="normal",
                                 anchor='nw')
        # Set image color so you can see it
        self.img.put('khaki',to=(0, 0, self.sizex, self.sizey))
        self.canvas.bind("<Button-1>",self.color_in)

    def color_in(self, event):
        # Paint a 2x2 square at the mouse position on image
        x, y = event.x, event.y
        self.img.put("black", to=(x-2, y-2, x+2, y+2))

paint = Paint()
paint.window.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.