2013-07-19 5 views
2

사용자가 캔버스 위젯에 텍스트를 입력 할 수 있어야 사용자가 새 텍스트를 입력 할 때 캔버스가 업데이트됩니다.Tkinter 캔버스 위젯에 텍스트 입력

여기까지 시도했지만 작동하지 않습니다.

먼저 나는 drawText

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

나는 또한 전역에 바인딩이이 mouseDown 방법은 내 방식에 startx, starty 위치를 반환

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

버튼-1 이벤트에 바인딩 된 mouseDown 방법을 캔버스 위젯은 다음과 같은 키 누르기를 캡처합니다.

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) 

그러나 오류가없고 캔버스에 아무것도 인쇄되지 않습니다.

답변

2

당신이하고 싶은 일은 꽤 복잡하고 잘 작동하려면 꽤 많은 코드가 필요합니다. 클릭 이벤트, 키 누르기 이벤트, 특수 키 누르기 이벤트 (예 : "Shift"및 "Ctrl"), "백 스페이스"및 이벤트 삭제 등을 처리해야합니다.

그럼에도 불구하고, 먼저 사용자가 입력 할 때 텍스트가 캔버스에 표시됩니다. 자, 당신의 전체 대본이 없기 때문에, 나는 당신의 물건을 그대로 사용할 수 없습니다. 그러나, 나는 가서 당신이 원하는 것을 정확하게하는 작은 앱을 만들었습니다. 캔버스에 어딘가에 클릭하고 입력을 시작하면 텍스트가 표시 볼 수

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

: 희망, 그것은 어디로 가야에 대해 어느 정도의 실마리를 제공 할 것이다. 그러나이 텍스트를 삭제 처리 할 수 ​​없습니다 (조금 까다 롭고 질문의 범위를 벗어납니다).

+0

이 답변이 작성된 이후로 몇 년이 지난 것을 알고 있습니다. 그럼에도 불구하고 모든 키 입력에 대해 새 텍스트 항목을 만들지 않아도된다는 사실을 지적하고자합니다. 캔버스 텍스트 항목을 편집 할 수 있습니다. 구현 방법은 http://effbot.org/zone/editing-canvas-text-items.htm을 참조하십시오. –

관련 문제