1.创建tk对象
2.设置一些位置,创建控件
3.利用pack或者place等不同放置功能将控件放置在相关位置
4.启动消息循环,不然无法显示win.mainloop()
#tkinter
import tkinter
#全局变量
str_var=None
def btn_click():
s=str_var.get()
print(s)
if __name__ == '__main__':
#创建Tk对象,显示窗口
win=tkinter.Tk()
#设置标题
win.title("Tkinter窗口")
#设置窗口大小及位置
win.geometry("800x600+100+100")#widthxheight+x+y
width=800
height=600
#获取屏幕的宽度和高度
screen_width=win.winfo_screenwidth()
screen_height=win.winfo_screenheight()
x=(screen_width-width)//2
y=(screen_height-height)//2
win.geometry("%dx%d+%d+%d"%(width,height,x,y))
#添加控件
lab=tkinter.Label(master=win,text='静态文本',background='red')
lab.pack(side=tkinter.LEFT)
lab=tkinter.Label(master=win,text='2nd静态文本')
lab.pack()
#按钮
btn=tkinter.Button(master=win,text='按钮',command=btn_click)#command=定义方法
btn.pack()
#文本框
str_var=tkinter.StringVar()
entry=tkinter.Entry(master=win,width=100,textvariable=str_var)#宽度为能显示字符的数量=100,textvariable类型为StringVar
entry.pack()
str_var.set("TOM")
#启动消息循环
win.mainloop()
from tkinter import ttk
import tkinter
#全局变量
str_var1=None
str_var2=None
str_var=None
def btn_click():
s1=str_var1.get()
s2=str_var2.get()
if comboxlist.get()=='+':
str_var.set(float(s1)+float(s2))
elif comboxlist.get()=='-':
str_var.set(float(s1) - float(s2))
elif comboxlist.get()=='*':
str_var.set(float(s1) * float(s2))
elif comboxlist.get() == '/':
str_var.set(float(s1) / float(s2))
elif comboxlist.get() == '**':
str_var.set(float(s1) ** float(s2))
def btn_clear():
str_var1.set("")
str_var2.set("")
str_var.set("")
if __name__ == '__main__':
#创建Tk对象,显示窗口
win=tkinter.Tk()
#设置标题
win.title("加法计算器")
width=400
height=200
#获取屏幕的宽度和高度
screen_width=win.winfo_screenwidth()
screen_height=win.winfo_screenheight()
x=(screen_width-width)//2
y=(screen_height-height)//2
win.geometry("%dx%d+%d+%d"%(width,height,x,y))
#文本框1
str_var1 = tkinter.StringVar()
entry = tkinter.Entry(master=win, width=10, textvariable=str_var1)
entry.place(x=50,y=50,width=50,height=25)
# 下拉
comvalue = tkinter.StringVar()
comboxlist = ttk.Combobox(win, textvariable=comvalue)
comboxlist["values"] = ("+", "-", "*", "/","**")
comboxlist.current(0)
comboxlist.place(x=110,y=50,width=50,height=25)
#文本框2
str_var2 = tkinter.StringVar()
entry = tkinter.Entry(master=win, width=10, textvariable=str_var2)
entry.place(x=170,y=50,width=50,height=25)
#等号按钮
btn = tkinter.Button(master=win, text='=', command=btn_click) # command=定义方法
btn.place(x=230,y=50,width=50,height=25)
#文本框3结果
str_var = tkinter.StringVar()
entry = tkinter.Entry(master=win, width=10, textvariable=str_var)
entry.place(x=290,y=50,width=50,height=25)
# 清空按钮
btn = tkinter.Button(master=win, text='清空', command=btn_clear) # command=定义方法
btn.place(x=330, y=150, width=50, height=25)
win.mainloop()