1.序列應用——猜數字遊戲

import tkinter as tk
import sys
import random
import re

number = random.randint(0,1024)
running = True
num = 0
nmaxn = 1024
nminn = 0

def eBtnClose(event):
    root.destroy()

def eBtnGuess(event):                        # 「按鈕事件函數
    global nmaxn                             # 全局變量
    global nminn
    global num
    global running
    if running:
        val_a = int(entry_a.get())           # 獲取猜的數字並轉換成數字
        if val_a == number:
            labelqval("恭喜答對了!")
            num += 1
            running = False
            numGuess()                       # 顯示猜的次數
        elif val_a < number:                 # 猜小了
            if val_a >nminn:
                nminn = val_a                # 修改提示猜想範圍的最小數
                num += 1
                labelqval("小了哦,請輸入" + str(nminn) + "" + str(nmaxn) + "之間任意整數:")
        else:
            if val_a < nmaxn:
                nmaxn = val_a                # 修改提示猜想範圍的最大數
                num += 1
                labelqval("大了哦,請輸入" + str(nminn) + "" + str(nmaxn) + "之間任意整數:")
    else:
        labelqval('你已經答對啦。。。')

#顯示猜的次數
def numGuess():
    if num == 1:
        labelqval('一次答對!')
    elif num < 10:
        labelqval('==十次之內就答對了,牛。。。嘗試次數:' + str(num))
    else:
        labelqval('還行哦嘗試次數:' + str(num))

def labelqval(vText):
    label_val_q.config(label_val_q, text = vText)        # 修改提示標籤文字

root = tk.Tk(className = "猜數字遊戲")
root.geometry("400x90+200+200")

line_a_tip = tk.Frame(root)
label_tip_max = tk.Label(line_a_tip,text=nmaxn)
label_tip_min = tk.Label(line_a_tip,text=nminn)
label_tip_max.pack(side = "top",fill = "x")
label_tip_min.pack(side = "bottom",fill = "x")
line_a_tip.pack(side = "left",fill = "y")

line_question = tk.Frame(root)
label_val_q = tk.Label(line_question, width = "80")               # 提示標籤
label_val_q.pack(side = "left")
line_question.pack(side = "top",fill = "x")

line_input = tk.Frame(root)
entry_a = tk.Entry(line_input, width = "40")                   # 單行輸入文本框
btnGuess = tk.Button(line_input, text = "")                  # 「按鈕
entry_a.pack(side = "left")
entry_a.bind('<Return>', eBtnGuess)                      # 綁定事件
btnGuess.bind('<Button-1>', eBtnGuess)                   # 「按鈕
btnGuess.pack(side = "left")
line_input.pack(side = "top",fill = "x")

line_btn = tk.Frame(root)
btnClose = tk.Button(line_btn, text = "關閉")                 # 「關閉按鈕
btnClose.bind('<Button-1>', eBtnClose)
btnClose.pack(side = "left")
line_btn.pack(side="top")

labelqval("請輸入01024之間任意整數:")
entry_a.focus_set()

print(number)
root.mainloop()

相關文章
相關標籤/搜索