python之tkinter基礎教程(一)

tkinter基礎教程(一)

1.我的第一個窗口程序

import tkinter as tk

app = tk.Tk()    #生成一個主窗口
app.title("My first window")    #主窗口的標題

theLabel = tk.Label(app,text="我的第一個窗口程序")
theLabel.pack() #自動調節窗口位置

app.mainloop()    #窗口的主事件觸發

2改進版的小程序

import tkinter as tk

#創建一個類進行封裝
class App:
    def __init__(self,master):
        frame = tk.Frame(master)
        frame.pack()
        
        self.hi_there = tk.Button(master,text='打招呼',fg='blue')
        self.hi_there.pack()

root = tk.Tk()
app = App(root)

root.mainloop()

 

3.進一步改進 (上一個點擊按鈕沒反應,這個有)

import tkinter as tk

class App:
    def __init__(self,master):
        frame = tk.Frame(master)
        frame.pack()
        
        self.hi_there = tk.Button(master,text='打招呼',fg='blue',command=self.say_hello)
        self.hi_there.pack()
    
    def say_hello(self):
        print('互聯網的廣大朋友們大家好,我是菜瓜')

root = tk.Tk()
app = App(root)

root.mainloop()

 

 

4.改變按鈕的位置

pack()內有side 可以調整 frame的位置

padx與pady設置距離主窗口的距離

bg設置背景

fg設置字體顏色

import tkinter as tk

class App:
    def __init__(self,master):
        frame = tk.Frame(master)
        #pack()中的side設置在左邊,右邊,上下,padx,pady設置距離主窗口的距離
        frame.pack(side=tk.LEFT,padx = 3,pady = 3) 
        
        self.hi_there = tk.Button(master,text='打招呼',fg='white',
        bg='black',command=self.say_hello)#bg設置按鈕的背景,fg設置字體顏色
        self.hi_there.pack()
    
    def say_hello(self):
        print('互聯網的廣大朋友們大家好,我是菜瓜')

root = tk.Tk()
app = App(root)

root.mainloop()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章