Skip to main content
 首页 » 编程设计

python之在 Tkinter Canvas 小部件中键入文本

2024年11月01日10insus

我需要允许用户在 Canvas 小部件中键入文本,使 Canvas 在用户键入新文本时更新。

这是我到目前为止尝试过的方法,但无法正常工作。

首先我有一个绑定(bind)到 Button-1 事件的 mouseDown 方法

widget.bind(self.canvas, "<Button-1>", self.mouseDown) 

此mouseDown 方法将startx, starty 位置返回到我的方法drawText

def drawText(self, x, y, fg): 
    self.currentObject = self.canvas.create_text(x,y,fill=fg,text=self.typedtext) 

我在 Canvas 小部件上也有一个全局绑定(bind),可以像这样捕获任何按键:

Widget.bind(self.canvas, "<Any KeyPress>", self.currentTypedText) 
 
def currentTypedText(self, event): 
    self.typedtext = str(event.keysym) 
    self.drawText(self, self.startx, self.starty,self.foreground) 

但是没有错误, Canvas 上没有打印任何内容。

请您参考如下方法:

您想要做的事情非常复杂,需要大量代码才能正常工作。您将需要处理点击事件、按键事件、特殊按键事件(例如“Shift”和“Ctrl”)、“退格”和删除事件,等等。

然而,首先是第一个,即让文本在用户键入时显示在 Canvas 中。现在,由于我没有您的完整脚本,我无法按原样使用您的东西。但是,我去制作了自己的小应用程序,它完全可以满足您的需求。希望它能为我们指明方向:

from Tkinter import * 
 
class App(Tk): 
 
    def __init__(self): 
        Tk.__init__(self) 
        # self.x and self.y are the current mouse position 
        # They are set to None here because nobody has clicked anywhere yet. 
        self.x = None 
        self.y = None 
        self.makeCanvas() 
        self.bind("<Any KeyPress>", lambda event: self.drawText(event.keysym)) 
 
    def makeCanvas(self): 
        self.canvas = Canvas(self) 
        self.canvas.pack() 
        self.canvas.bind("<Button-1>", self.mouseDown) 
 
    def mouseDown(self, event): 
        # Set self.x and self.y to the current mouse position 
        self.x = event.x 
        self.y = event.y 
 
    def drawText(self, newkey): 
        # The if statement makes sure we have clicked somewhere. 
        if None not in {self.x, self.y}: 
            self.canvas.create_text(self.x, self.y, text=newkey) 
            # I set x to increase by 5 each time (it looked the nicest). 
            # 4 smashed the letters and 6 left gaps. 
            self.x += 5 
 
App().mainloop() 

单击 Canvas 中的某处并开始输入后,您将看到文本出现。但是请注意,我没有启用它来处理文本删除(这有点棘手并且超出了您的问题范围)。