iT邦幫忙

3

如何利用tkinter幫Python設計介面(2)-按鈕、標籤、變數

前言:

透過簡單的加減法,讓自己熟悉如何活用tkinter的特殊變數。

工作環境:

-Windows 10
-Anaconda 2020.02
-Python 3.6.10
-Spyder 4.1.1

教程(1)-建立並佈置物件:

如何建立tkinter的物件,並且佈置在視窗上。
https://ithelp.ithome.com.tw/upload/images/20200325/20124766LB688NXRKd.jpg

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

# 匯入函式庫
import tkinter as tk

# 宣告
root = tk.Tk()

# 視窗標題
root.title('Lesson 1')
# 視窗初始大小
root.geometry('800x600')
# 視窗[左右, 上下]是否可拉大拉小,若都為0則視窗右上角的最大化按鈕會無法點擊
root.resizable(0, 1)

# 建議標籤
lab_result = tk.Label(root, text='666')
# 建立按鈕
bt_plus = tk.Button(root, text='+1')
bt_min = tk.Button(root, text='-1')

# 為物件分配位置
lab_result.pack()# 自動佈置
bt_plus.pack()
bt_min.place(x=387, y=75)# 手動佈置


# 自動刷新畫面
root.mainloop()

教程(2)-如何為物件綁定事件並且宣告變數:

示範透過按鈕來變更邊謙上顯示的數字,IntVar()是用來顯示加減結果的,因為我們無法直接用一般變數來改變標籤顯示結果:
https://ithelp.ithome.com.tw/upload/images/20200325/20124766E1Rxn3bLaL.jpg

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

# 匯入函式庫
import tkinter as tk

def plus_():
    global k
    k = k + 1
    result.set(k)
    
def min_():
    global k
    k = k - 1
    result.set(k)   

# 宣告
root = tk.Tk()

# 視窗標題
root.title('Lesson 2')
# 視窗初始大小
root.geometry('800x600')
# 視窗[左右, 上下]是否可拉大拉小,若都為0則視窗右上角的最大化按鈕會無法點擊
root.resizable(0, 1)

# 定義變數k
k = 0
# 定義tkinter專屬變數result
result = tk.IntVar()
# 將變數k單次傳值至tkinter專屬變數result
result.set(k)
# 建立標籤
lab_result = tk.Label(root, text='textvariable有優先權,所以這句不會顯示', textvariable=result)
# 建立按鈕,並且綁定事件
bt_plus = tk.Button(root, text='+1', command=plus_)
bt_min = tk.Button(root, text='-1', command=min_)

# 為物件分配位置
lab_result.pack()# 自動佈置
bt_plus.pack()
bt_min.place(x=387, y=75)# 手動佈置


# 自動刷新畫面
root.mainloop()

當然還有StrVar()可以用,只是記得要用int()作轉換呦:

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

# 匯入函式庫
import tkinter as tk

def plus_():
    global k
    k = k + 1
    result.set(int(k))
    
def min_():
    global k
    k = k - 1
    result.set(int(k))   

# 宣告
root = tk.Tk()

# 視窗標題
root.title('Lesson 1')
# 視窗初始大小
root.geometry('800x600')
# 視窗[左右, 上下]是否可拉大拉小,若都為0則視窗右上角的最大化按鈕會無法點擊
root.resizable(0, 1)

# 定義變數k
k = 0
# 定義tkinter專屬變數result
result = tk.StringVar()
# 將變數k單次傳值至tkinter專屬變數result
result.set(int(k))
# 建議標籤
lab_result = tk.Label(root, text='textvariable有優先權', textvariable=result)
# 建立按鈕
bt_plus = tk.Button(root, text='+1', command=plus_)
bt_min = tk.Button(root, text='-1', command=min_)

# 為物件分配位置
lab_result.pack()# 自動佈置
bt_plus.pack()
bt_min.place(x=387, y=75)# 手動佈置


# 自動刷新畫面
root.mainloop()

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言