iT邦幫忙

2025 iThome 鐵人賽

DAY 4
0

今天就是把昨天跟前天做個簡單的整合

import customtkinter
import google.generativeai as genai

# ========== 設定 Gemini ==========
genai.configure(api_key="你的API KEY")
model = genai.GenerativeModel(model_name="models/gemini-2.5-flash")

# ========== 建立 GUI ==========
def button_click():
    input_text = entry.get()
    if input_text.strip() == "":
        output_label.configure(text="⚠️ 請輸入文字!")
        return

    try:
        # 呼叫 Gemini API
        response = model.generate_content(input_text)
        answer = response.text
    except Exception as e:
        answer = f"發生錯誤:{e}"

    # 顯示輸出在 Label
    output_label.configure(text=f"Gemini 回覆:\n{answer}")

# 設定主題外觀
customtkinter.set_appearance_mode("light")

# 建立主視窗
app = customtkinter.CTk()
app.title("Gemini AI 助手")
app.geometry("600x400")

# 標題
title_label = customtkinter.CTkLabel(
    app,
    text="CustomTkinter + Gemini AI",
    text_color="#ff5733",
    font=("timesnewroman", 28, "italic")
)
title_label.pack(pady=20)

# 輸入框
entry = customtkinter.CTkEntry(
    app,
    placeholder_text="請輸入你的問題",
    fg_color="#e0e0e0",
    corner_radius=10,
    width=400
)
entry.pack(pady=10)

# 提交按鈕
button = customtkinter.CTkButton(
    app,
    text="送出問題",
    command=button_click,
    fg_color="#4CAF50",
    hover_color="#c8d628",
    text_color="#ffffff",
    corner_radius=15,
    width=200
)
button.pack(pady=20)

# 顯示輸出的 Label
output_label = customtkinter.CTkLabel(
    app,
    text="Gemini 回覆會顯示在這裡",
    text_color="#333333",
    font=("Arial", 16),
    wraplength=500,   # 自動換行
    justify="left"
)
output_label.pack(pady=20)

app.mainloop()

結果如下圖
https://ithelp.ithome.com.tw/upload/images/20250918/20177921PIBtIoMy6Q.png


上一篇
DAY 3
下一篇
DAY 5
系列文
我的 AI 助手開發8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言