一、Entry部件基本介绍
Entry小部件是Tkinter的基本小部件,用于从应用程序的用户获取输入,即文本字符串。这个小部件允许用户输入一行文本。如果用户输入的字符串比小部件的可用显示空间长,则将滚动内容。这意味着不能看到字符串的整体。箭头键可用于移动到字符串的不可见部分。如果要输入多行文本,则必须使用文本小部件。
下面给大家介绍一下简单的Entry输入框创建:
importtkinterastk windon = tk.Tk() tk.Label(windon, text= " 账号 " ).grid(row=0) tk.Label(windon, text= **"** **密码** **"** ).grid(row=1) e1 = tk.Entry(windon) e2 = tk.Entry(windon) e1.grid(row=0, column=1) e2.grid(row=1, column=1) windon.mainloop() |
---|
下面就是运行结果
|
import tkinter as tk
defshow_entry_fields():
print("账号: %s\n密码: %s" % (e1.get(), e2.get()))
windon = tk.Tk()
tk.Label(windon,
text="账号").grid(row=0)
tk.Label(windon,
text="密码").grid(row=1)
e1 = tk.Entry(windon)
e2 = tk.Entry(windon,show = '*')
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
tk.Button(windon,
text='Quit',
command=windon.quit).grid(row=3,
column=0,
sticky=tk.W,
pady=4)
tk.Button(windon,
text='Show', command=show_entry_fields).grid(row=3,
column=1,
sticky=tk.W,
pady=4)
tk.mainloop()
下面为运行结果:
|
from tkinter import *
#创建横条型框架
defframe(root, side):
windon = Frame(root)
windon.pack(side=side, expand=YES, fill=BOTH)
return windon
#创建按钮
defbutton(root, side, text, command=None):
windon = Button(root, text=text, command=command)
windon.pack(side=side, expand=YES, fill=BOTH)
return windon
#继承了Frame类,初始化程序界面的布局
classCalculator(Frame):
def __init__(self):
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('Simple Calculater')
display = StringVar()
#添加输入框
Entry(self, relief=SUNKEN,
textvariable=display).pack(side=TOP, expand=YES,fill=BOTH)
#添加横条型框架以及里面的按钮
for key in ('123', '456', '789', '-0.'):
keyF = frame(self, TOP)
for char in key:
button(keyF, LEFT, char, lambda w=display, c=char: w.set(w.get() + c))
opsF = frame(self, TOP)
for char in '+-*/=':
if char == '=':
btn = button(opsF, LEFT, char)
btn.bind('<ButtonRelease - 1>', lambda e, s=self, w=display: s.calc(w), '+')
else:
btn = button(opsF, LEFT, char, lambda w=display, s='%s' % char: w.set(w.get() + s))
clearF = frame(self, BOTTOM)
button(clearF, LEFT, 'clear', lambda w=display: w.set(''))
def calc(self, display):
display.set(eval(display.get()))
if__name__ == '__main__':
Calculator().mainloop()