Reprint a basic code of Python interface design

#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import Spinbox
from tkinter import messagebox as mBox


#由于tkinter中没有ToolTip功能,所以自定义这个功能如下
class ToolTip(object):
    def __init__(self, widget):
        self.widget = widget
        self.tipwindow = None
        self.id = None
        self.x = self.y = 0


    def showtip(self, text):
        "Display text in tooltip window"
        self.text = text
        if self.tipwindow or not self.text:
            return
        x, y, _cx, cy = self.widget.bbox("insert")
        x = x + self.widget.winfo_rootx() + 27
        y = y + cy + self.widget.winfo_rooty() +27
        self.tipwindow = tw = tk.Toplevel(self.widget)
        tw.wm_overrideredirect(1)
        tw.wm_geometry("+%d+%d" % (x, y))


        label = tk.Label(tw, text=self.text, justify=tk.LEFT,
                      background="#ffffe0", relief=tk.SOLID, borderwidth=1,
                      font=("tahoma", "8", "normal"))
        label.pack(ipadx=1)


    def hidetip(self):
        tw = self.tipwindow
        self.tipwindow = None
        if tw:
            tw.destroy()
            
#===================================================================          
def createToolTip( widget, text):
    toolTip = ToolTip(widget)
    def enter(event):
        toolTip.showtip(text)
    def leave(event):
        toolTip.hidetip()
    widget.bind('<Enter>', enter)
    widget.bind('<Leave>', leave)


# Create instance
win = tk.Tk()   


# Add a title       
win.title("Python 图形用户界面")


# Disable resizing the GUI
win.resizable(0,0)


# Tab Control introduced here --------------------------------------
tabControl = ttk.Notebook(win)          # Create Tab Control


tab1 = ttk.Frame(tabControl)            # Create a tab 
tabControl.add(tab1, text='第一页')      # Add the tab


tab2 = ttk.Frame(tabControl)            # Add a second tab
tabControl.add(tab2, text='第二页')      # Make second tab visible


tab3 = ttk.Frame(tabControl)            # Add a third tab
tabControl.add(tab3, text='第三页')      # Make second tab visible


tabControl.pack(expand=1, fill="both")  # Pack to make visible
# ~ Tab Control introduced here -----------------------------------------


#---------------Tab1控件介绍------------------#
# We are creating a container tab3 to hold all other widgets
monty = ttk.LabelFrame(tab1, text='控件示范区1')
monty.grid(column=0, row=0, padx=8,pads = 4)


# Modified Button Click Function
def clickMe():
    action.configure(text='Hello\n ' + name.get())
    action.configure(state='disabled')    # Disable the Button Widget


# Changing our Label
ttk.Label(monty, text="输入文字:").grid(column=0, row=0, sticky='W')


# Adding a Textbox Entry widget
name = tk.StringVar()
nameEntered = ttk.Entry(monty, width=12, textvariable=name)
nameEntered.grid(column=0, row=1, sticky='W')


# Adding a Button
action = ttk.Button(monty,text="点击之后\n按钮失效",width=10,command=clickMe)   
action.grid(column=2,row=1,rowspan=2,ipady=7)


ttk.Label(monty, text="请选择一本书:").grid(column=1, row=0,sticky='W')


# Adding a Combobox
book = tk.StringVar()
bookChosen = ttk.Combobox(monty, width=12, textvariable=book)
bookChosen['values'] = ('Ordinary World', 'Dear Andre', 'See',' White night line')
bookChosen.grid(column=1, row=1)
bookChosen.current(0) #Set the initial display value, the value is the subscript of the tuple ['values']
bookChosen.config(state='readonly') #Set to read-only mode


# Spinbox callback 
def _spin():
    value = spin.get()
    #print(value)
    scr.insert(tk.INSERT, value + '\n')


def _spin2():
    value = spin2. get()
    #print(value)
    scr.insert(tk.INSERT, value + '\n')
     
# Adding 2 Spinbox widget using a set of values
​​spin = Spinbox(monty, from_=10,to=25, width=5 , bd=8,  command=_spin) 
spin.grid(column=0, row=2)


spin2 = Spinbox(monty, values=('Python3 entry', 'C language','C++', 'Java', 'OpenCV'), width=13, bd= 3, command=_spin2) 
spin2.grid(column=1, row=2,sticky='W')
 
# Using a scrolled Text control    
scrolW = 30; scrolH = 5
scr = scrolledtext.ScrolledText(monty, width=scrolW, height =scrolH, wrap=tk.WORD)
scr.grid(column=0, row=3, sticky='WE', columnspan=3)


# Add Tooltip
createToolTip(spin, 'This is a Spinbox.')
createToolTip(spin2, 'This is a Spinbox.')
createToolTip(action, 'This is a Button.')
createToolTip(nameEntered, 'This is an Entry.')
createToolTip(bookChosen, 'This is a Combobox.' )
createToolTip(scr, 'This is a ScrolledText.')


# Control the distance between controls at one time
for child in monty.winfo_children(): 
    child.grid_configure(padx=3,pady=1)
# Control the distance between individual controls
action.grid(column=2,row= 1,rowspan=2,padx=6)
#---------------Introduction of Tab1 control-------------------#




#- --------------Introduction to Tab2 control ------------------#
# We are creating a container tab3 to hold all other widgets -- Tab2
monty2 = ttk.LabelFrame(tab2, text='Control Demonstration Area 2')
monty2.grid(column=0, row=0, padx=8, pady=4)
# Creating three checkbuttons
chVarDis = tk.IntVar()
check1 = tk.Checkbutton(monty2, text="Disabled option", variable=chVarDis, state='disabled')
check1.select()  
check1.grid(column=0, row=0, sticky=tk.W)                 


chVarUn = tk .IntVar()
check2 = tk.Checkbutton(monty2, text="遵从内心", variable=chVarUn)
check2.deselect()   #Clears (turns off) the checkbutton.
check2.grid(column=1, row=0, sticky=tk.W )                  
 
chVarEn = tk.IntVar()
check3 = tk.Checkbutton(monty2, text="屈于现实", variable=chVarEn)
check3.deselect()
check3.grid(column=2, row=0, sticky=tk.W)                 


# GUI Callback function 
def checkCallback(*ignoredArgs):
    # only enable one checkbutton
    if chVarUn.get(): check3.configure(state='disabled')
    else:             check3.configure(state='normal')
    if chVarEn.get(): check2.configure(state='disabled')
    else:             check2.configure(state='normal') 
 
# trace the state of the two checkbuttons #? ?
chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback())    
chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback())   


# Radiobutton list
values ​​= ["Rich, strong and democratic", " Civilization and harmony", "liberty and equality", "justice and rule of law", "patriotism and dedication", "integrity and friendliness"]


# Radiobutton callback function
def radCall():
    radSel=radVar.get()
    if radSel == 0: monty2.configure( text='prosperity, strength and democracy')
    elif radSel == 1: monty2.configure(text='civilization and harmony')
    elif radSel == 2: monty2.configure(text='freedom and equality')
    elif radSel == 3: monty2.configure (text='Justice and Rule of Law')
    elif radSel == 4: monty2.configure(text='



# create three Radiobuttons using one variable
radVar = tk.IntVar()


# Selecting a non-existing index value for radVar
radVar.set(99)    


# Creating all three Radiobutton widgets within one loop
for col in range(4):
    #curRad = 'rad' + str(col)  
    curRad = tk.Radiobutton(monty2, text=values[col], variable=radVar, value=col, command=radCall)
    curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
for col in range(4,6):
    #curRad = 'rad' + str(col)  
    curRad = tk.Radiobutton(monty2, text=values[col], variable=radVar, value=col, command=radCall)
    curRad.grid(column=col-4, row=7, sticky=tk.W, columnspan=3)


style = ttk.Style()
style.configure("BW.TLabel", font=("Times", "10",'bold'))
ttk.Label(monty2, text="Socialist Core Values",style="BW.TLabel"). grid(column=2, row=7,columnspan=2, sticky=tk.EW)


# Create a container to hold labels
labelsFrame = ttk.LabelFrame(monty2, text='nested area')
labelsFrame.grid(column=0 , row=8,columnspan=4)
 
# Place labels into the container element - vertically
ttk.Label(labelsFrame, text="You are only 25, you can be whoever you want.").grid(column=0 , row=0)
ttk.Label(labelsFrame, text="Don't care about the gains and losses of one city and one pool, be persistent.").grid(column=0, row=1,sticky=tk.W)


# Add some space around each label
for child in labelsFrame.winfo_children(): 
    child.grid_configure(padx=8, pady=4)
#---------------Introduction to Tab2 control-------------------#




#---------------Tab3控件介绍------------------#
tab3 = tk.Frame(tab3, bg='#AFEEEE')
tab3.pack()
for i in range(2):
    canvas = 'canvas' + str(col)
    canvas = tk.Canvas(tab3, width=162, height=95, highlightthickness=0, bg='#FFFF00')
    canvas.grid(row=i, column=i)
#---------------Tab3控件介绍------------------#




#----------------菜单栏介绍-------------------#    
# Exit GUI cleanly
def _quit():
    win.quit()
    win.destroy()
    exit()
    
# Creating a Menu Bar
menuBar = Menu(win)
win.config(menu=menuBar)


# Add menu items
fileMenu = Menu(menuBar, tearoff=0)
, 'You have selected "Yes", thank you for participating!     ') else:



















        mBox.showinfo('Show selection result', 'You chose "No", thank you for participating!')


# Add another Menu to the Menu Bar and an item
msgMenu = Menu(menuBar, tearoff=0)
msgMenu.add_command(label= "Notification Box", command=_msgBox1)
msgMenu.add_command(label="Warning Box", command=_msgBox2)
msgMenu.add_command(label="Error Box", command=_msgBox3)
msgMenu.add_separator()
msgMenu.add_command(label= "Judgment dialog", command=_msgBox4)
menuBar.add_cascade(label="message box", menu=msgMenu)
#----------------Menu bar introduction----- --------------#




# Change the main windows icon
win.iconbitmap(r'C:\Users\feng\Desktop\yan.ico')


# Place cursor into name Entry
nameEntered.       focus()      
#======================
# Start GUI
#=====================
win.mainloop ()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325888679&siteId=291194637