我是Python类和tkinter
的新手。我正在尝试使用python GUI工具提示类-由@ crxguy52开发的Class CreateToolTip
并实现为GUI类。 GUI类很简单:Label
,Entry
和Button
。
import tkinter as tk
class CreateToolTip(object):
"""
create a tooltip for a given widget
"""
def __init__(self, widget=None, text=None):
self.waittime = 500
self.wraplength = 180
self.widget = widget
self.text = text
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
self.widget.bind("<ButtonPress>", self.leave)
self.id = None
self.tw = None
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(self.waittime, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def showtip(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
# creates a toplevel window
self.tw = tk.Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(self.tw, text=self.text, justify='left',
background="#ffffff", relief='solid', borderwidth=1,
wraplength = self.wraplength)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tw
self.tw= None
if tw:
tw.destroy()
class GUI(tk.Frame):
def __init__(self, master=None, Frame=None):
tk.Frame.__init__(self, master)
super(GUI,self).__init__()
self.createWidgets()
self.button_close = tk.Button(text='Close', command=self.quitButton)\
.grid(row=9, column=0, sticky='W', padx=5, pady=5)
self.button_send = tk.Button(text='Send', command=self.sendButton)\
.grid(row=9, column=3, sticky='E', padx=5, pady=5)
def quitButton(self):
self.master.destroy()
import sys
sys.exit()
def sendButton(self):
global alt
alt = self.alt.get()
self.master.destroy()
def createWidgets(self):
import os
# alt
lbl = tk.Label(text='Start at ').grid(row=1, sticky='W')
lbl_ttp = CreateToolTip(lbl,'hello world')
self.alt = tk.Entry(width=12)
self.alt.grid(row=1, column=1)
self.alt.focus()
self.alt.insert(0,'5000')
app = GUI()
app.mainloop()
print (alt)
为了使代码整洁,我保留了原始的Tooltip类并创建了GUI。然后它会遇到错误:
Traceback (most recent call last):
File "D:/User/test3.py", line 88, in <module>
app = GUI()
File "D:/User/test3.py", line 62, in __init__
self.createWidgets()
File "D:/User/test3.py", line 81, in createWidgets
lbl_ttp = CreateToolTip(lbl,'hello world')
File "D:/User/test3.py", line 13, in __init__
self.widget.bind("<Enter>", self.enter)
AttributeError: 'NoneType' object has no attribute 'bind'
由bind
类的__init__
中的CreateToolTip
引起。我应该如何更改该语句:lbl_ttp = CreateToolTip(lbl,'hello world')
使它起作用?谢谢大家。
该错误在“ tk.Label(text ='从'开始'..grid(row = 1,sticky ='W')”行上。
Label / Button等对象的网格方法返回None,因此__init__中的“ master”也为None,这就是为什么绑定调用失败的原因。
您可以通过将行更改为来修复它
lbl = tk.Label(text='Start at ')
lbl.grid(row=1, sticky='W')
lbl_ttp = CreateToolTip(lbl,'hello world')