#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import font
def output_to_console(text):
global console
console.insert(tk.END, text + "\n")
console.see(tk.END) # 自動滾動到最底部
def clear_console():
global console
console.delete(1.0, tk.END) # 清除所有文本
def create_window():
global console # 將 console 設置為全域變數以便外部函數訪問
# 創建主視窗
root = tk.Tk()
root.title("測試程式")
# 設定視窗大小
window_width = 400
window_height = 400
# 獲取螢幕寬高
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# 計算視窗起始位置
position_top = int(screen_height / 2 - window_height / 2)
position_right = int(screen_width / 2 - window_width / 2)
# 設定視窗位置
root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
# 定義按鈕點擊函數
def on_button_click():
label.config(text="測試進行中...")
console.insert(tk.END, "開始測試\n")
button1.config(state=tk.DISABLED)
button2.config(state=tk.NORMAL)
def on_button2_click():
label.config(text="測試已停止...")
console.insert(tk.END, "停止測試\n")
button1.config(state=tk.NORMAL)
button2.config(state=tk.DISABLED)
def on_button3_click():
label.config(text="測試未開始...")
clear_console()
# 創建框架來包含 console 和滾動條
outer_frame = tk.Frame(root, width=380, height=260)
outer_frame.pack_propagate(False)
outer_frame.pack(pady=10)
# 創建框架來包含滾動條和文本控件
console_frame = tk.Frame(outer_frame, bg="light yellow", bd=1, relief="solid")
console_frame.pack(fill=tk.BOTH, expand=True, side=tk.LEFT)
# 添加空白的 Frame 用來隱藏右側邊框
empty_frame = tk.Frame(console_frame, bg="light yellow", width=2)
empty_frame.pack(side=tk.RIGHT, fill=tk.Y)
# 添加滾動條
scrollbar = tk.Scrollbar(console_frame, bg="light yellow", bd=0, relief="flat")
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 添加一個類似 console 的輸出視窗,並設置為 300x20,改變背景顏色和邊框
text_font = font.Font(family="Helvetica", size=14)
console = tk.Text(console_frame, wrap=tk.WORD, font=text_font, width=48, height=10, bg="light yellow", bd=0, relief="flat", highlightthickness=0, yscrollcommand=scrollbar.set)
console.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# 設置滾動條關聯
scrollbar.config(command=console.yview)
# 添加一個標籤
label = tk.Label(root, text="測試未開始...")
label.pack(pady=10)
# 創建按鈕框架
button_frame = tk.Frame(root)
button_frame.pack(pady=10)
# 創建按鈕字體,將字型大小設置為 20(假設原大小為 10)
button_font = font.Font(size=20)
# 添加按鈕到框架中
button1 = tk.Button(button_frame, text="開始", font=button_font, command=on_button_click)
button1.grid(row=0, column=0, padx=5)
button2 = tk.Button(button_frame, text="停止", font=button_font, command=on_button2_click, state=tk.DISABLED)
button2.grid(row=0, column=1, padx=5)
# 添加清除 console 的按鈕
clear_button = tk.Button(button_frame, text="清除", font=button_font, command=on_button3_click)
clear_button.grid(row=0, column=2, padx=5)
# 運行主循環
output_to_console("程式已準備完成")
root.mainloop()
# 呼叫函數來創建視窗
if __name__ == "__main__":
create_window()
留言
張貼留言