我想顯示列表框的選定項目的文本到畫布中。當我將列表框綁定到輔助事件處理程序時,它會拋出屬性錯誤:CLASS對象沒有「HELPER EVENT HANDLER」屬性。如何使用Python3x tkiner在畫布中顯示列表框項目的文本?
我要的是如下:
1)雙擊列表框中的左側有一個項目,它的文本應顯示在畫布上。這一行代碼給我造成了所有的麻煩。
lstbox.bind("<Double-Button-1>", self.OnDouble)
你能幫我解決這個錯誤嗎?
2)我相信必須有一種方法可以使列表框上的行高度大於它在我的應用程序中出現的高度。但是,我不知道該怎麼做。我試過提供幾個選項,但這些選項不被tkinter識別。你能告訴我怎麼做嗎?
下面是代碼:
import tkinter as tk
languages = ['Mandarin', 'English', 'French']
class LanguageFamilies(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
canv = tk.Canvas(self, width=675, height=530, bg="white", relief="sunken")
canv.config(scrollregion=(0,0,300,650), highlightthickness=0)
canv.pack(side="right", expand=True, fill="both")
# Create scroll bar
sbar = tk.Scrollbar(self)
canv.config(yscrollcommand=sbar.set)
sbar.config(command=canv.yview)
sbar.pack(side="right", fill="both")
# Create Scroll List
lstbox = tk.Listbox(self, width=240, height=530, relief="sunken", font="Courier")
lst_scrollbar = tk.Scrollbar(self)
lstbox.config(yscrollcommand=lst_scrollbar.set)
lst_scrollbar.config(command=lstbox.yview)
lstbox.pack(side="left", expand=True, fill="both")
lst_scrollbar.pack(side="right", fill="both")
lstbox.bind("<Double-Button-1>", self.OnDouble) # THIS IS THE LINE CAUSING THE ERROR
# Add items to the lstbox
i = 0
while i < len(languages):
lstbox.insert(i, languages[i])
i += 1
# Create a text inside canvas
canv_id = canv.create_text(50, 50, font="Times 14", anchor="nw")
msg = "This is a text inside canvas."
canv.insert(canv_id, "end", msg)
#Binding Handler
def OnDouble(self, event):
self.widget = event.widget
selection = self.widget.curselection()
content = self.widget.get(selection[0])
print("You selected", content)
if __name__ == "__main__":
root = tk.Tk()
root.geometry("930x530")
root.title("Language Families")
LanguageFamilies(root).pack(fill="both", expand=True)
root.mainloop()
這是錯誤消息:
Traceback (most recent call last):
File "C:/Python33/new_stack_overflow.py", line 43, in <module>
LanguageFamilies(root).pack(fill="both", expand=True)
File "C:/Python33/new_stack_overflow.py", line 23, in __init__
lstbox.bind("<Double-Button-1>", self.OnDouble)
AttributeError: 'LanguageFamilies' object has no attribute 'OnDouble'
你的幫助是非常感謝!
你ndentation看起來很奇怪。你的'__init__'函數只有一行,其餘的是縮進的。那是故意的嗎?也許這是原因。還有其他縮進錯誤 - 與'def'語句在同一級別上進行編碼。也許你有一個標籤和空格的混合體,使得代碼看起來不同於你的計算機。 –
@BryanOakley,非常感謝您的評價。我認爲縮進問題是由將代碼複製到Web瀏覽器造成的。我已經從谷歌驅動器共享代碼。請在此處查看:https://drive.google.com/file/d/0Bzk3iitPNBruYnpKMFF4b1Fhbzg/view?usp=sharing先謝謝您! – Mohammed
請修復問題中的代碼。谷歌驅動器或該文件可能並不總是在附近。 –