Skip to main content

GUI

Tkinter

  • Tkinter是Python的標準GUI函數庫
  • 可以使用tkinter建立應用程式

視窗

from tkinter import *
top = Tk()
top.mainloop()
按鈕
from tkinter import *
gui = Tk(className='Python GUI Tutorial')
button = Button(gui, text='Submit', width=50, height=4, bg='#33cc33', fg='#FFFFFF', activebackground='#44DD44')
button.pack()
gui.mainloop()

文字方塊

from tkinter import *
gui = Tk()
L1 = Label(top, text="User name")
L1.pack(side=LEFT)
E1 = Entry(top, bd=5)
E1.pack(side=RIGHT)
gui.mainloop()

文字區塊

from tkinter import *
def onclick():
pass
gui = Tk()
text = Text(gui)
text.insert(INSERT, "Hello...")
text.insert(END, "Bye...")
text.pack()
text.tag_add("here", "1.0","1.4")
text.tag_add("start", "1.8","1.13")
text.tag_config("here", background='yellow', foreground='blue')
text.tag_config("start", background='black', foreground='green')
gui.mainloop()

卷軸

from tkinter import *
gui = Tk()
scrollbar = Srollbar(gui)
scrollbar.pack(side=RIGHT, fill=Y)
mylist = Listbox(gui, yscrollcommand = scrollbar.set)
for i in range(100):
mylist.insert(END, "Line "+ str(i))
mylist.pack(side=LEFT, fill=BOTH)
scrollbar.config(command = mylist.yview)
gui.mainloop()

選項鈕

from tkinter import *
def sel():
selection = "You selected "+ str(var.get())
label.config(text = selection)
gui = Tk()
var = IntVar()
R1 = RadioButton(gui, text="Option1", variable=var, value=1, command=sel)
R2 = RadioButton(gui, text="Option2", variable=var, value=2, command=sel)
R3 = RadioButton(gui, text="Option3", variable=var, value=3, command=sel)
R1.pack(anchor=W)
R2.pack(anchor=W)
R3.pack(anchor=W)
label = Label(gui)
label.pack()
gui.mainloop()

核取方塊

from tkinter import *
gui = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(gui, text="Music", variable=CheckVar1, onvalue=1, offvalue=0, height=5, width=20)
C2 = Checkbutton(gui, text="Video", variable=CheckVar2, onvalue=1, offvalue=0, height=5, width=20)
C1.pack()
C2.pack()
gui.mainloop()

對話方塊

from tkinter import *
messagebox.showinfo('title','message')
messagebox.showwarning('title','message')
messagebox.showerror('title','message')

圖形

from tkinter import *
load = Image.open('cat.jpg')
render = ImageTk.PhotoImage(load)
img = Label(self, image=render)
img.image = render
img.place(x=0,y=0)

功能表

from tkinter import *
def donothing():
filewin = Toplevel(gui)
button = Button(filewin, text="do nothing")
button.pack()
gui = Tk()
menubar = Menu(gui)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save As...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=gui.quit)
gui.config(menu=menubar)
gui.mainloop()