自制tkinter输入框Inputbox类

0 Comments

下面的的_Inputbox类能实例化一个输入对话框。

import tkinter as TK
class _Inputbox():
    def __init__(self, text=""):
        self._root = TK.Tk()
        self.get = ""                         # 自定义属性
        sw = self._root.winfo_screenwidth()   # 获取桌面宽度
        sh = self._root.winfo_screenheight()  # 获取桌面高度
        width = 300                           # 输入框的宽度
        height = 60                           # 输入框的高度
        startx = (sw - width) / 2             # 起始x坐标(居中显示用) 
        starty = (sh - height) /2             # 起始y坐标
        #if Turtle._screen is not None:
        #   scheight = Turtle._screen.window_height()
        #   starty = starty + scheight//2 -height//2 - 20
        self._root.geometry("%dx%d%+d%+d"%(width, height, startx, starty))
        self._root.title("输入框(inputbox)")
        self.label_file_name = TK.Label(self._root, text=text)
        self.label_file_name.pack()
        self.entry = TK.Entry(self._root,width=36)
        self.entry.pack(padx=10,side=TK.LEFT)
        self.entry.focus()
        self.entry.bind("", self.getinput)       # 绑定回车键 
        self.submit = TK.Button(self._root, text='确定',command=self.getinput) # 确定按钮
        self.submit.pack(padx=10,side=TK.RIGHT)          # 放在右边
        self._root.mainloop()
 
    def getinput(self):
        self.get = self.entry.get()
        self._root.destroy()
if __name__ == "__main__":
   
    i = _Inputbox('请输入字符串:')
    print(i.get)