視窗猜數字

2021-10-12 11:18:36 字數 1574 閱讀 2182

import tkinter as tk

import tkinter.messagebox

import random

# 設定主視窗

win = tk.tk()

win.title('welcome to 猜數字小遊戲')

win.geometry('300x400')

# 輸入框要輸入的內容

tk.label(win, text='請輸入你要猜的數:').place(x=100, y=170)

# 設定輸入框

var_step = tk.strin**ar()

var_step.set('')

entry_step = tk.entry(win, textvariable=var_step)

entry_step.place(x=100, y=200)

i = 5 # 猜測次數為5次

num2 = 0 # 全域性變數,用來存放系統生成的隨機數

def dispose():

conjecture_num = var_step.get() # 獲取使用者輸入的數

global i # 宣告變數 i 使其可以被修改

try:

conjecture_num = int(conjecture_num) # 把使用者猜的數變成整數賦給conjecture_num

if i % 5 == 0: # 每猜5次,重置系統的隨機數

num1 = int(random.randint(0, 100)) #生成隨機數

global num2 # 宣告全域性變數 num2 使其可被修改

num2 = num1

# 判斷使用者猜的數是否正確

if conjecture_num == int(num2):

tk.messagebox.showinfo(title='完成', message="恭喜你猜對了!")

i = 5 # 猜對的話,則次數變為5,準備重置隨機數

elif conjecture_num < int(num2):

i -= 1

tk.messagebox.showerror(title='error', message='數字太小了,您還剩{}次機會'.format(i % 5))

elif conjecture_num > (num2):

i -= 1

tk.messagebox.showerror(title='error', message='數字太大了,您還剩{}次機會'.format(i % 5))

except baseexception as e: # 若出現異常,彈出錯誤視窗

tk.messagebox.showerror(title='錯誤', message='請輸入整數')

# 設定按鈕

btn_dealt = tk.button(win, text='確認', command=dispose) # 點下按鈕,呼叫函式dispose

btn_dealt.place(x=100, y=290)

win.mainloop()

猜數字c 限制 猜數字小遊戲

週末看到的乙個猜數字小遊戲 挺有意思的 include include include using namespace std void start void getresults int i,j,life,maxrand char c void start life 5 玩家生命數 srand u...

猜數字遊戲

問題描述 猜數字遊戲 隨機出乙個兩位數,然後讓你猜,直到猜對為止。猜對後可以提示選擇是否再玩一次。include include using namespace std int main srand unsigned int time null int num rand 90 10 隨機出乙個兩位數...

猜數字遊戲

author 徐權 data 2015728 function 猜數字遊戲 實用平台 vs2012及以上 如果要移植到其他平台scanf s和puts s 應改為scanf和puts即可 include include include include define n 5 定義陣列大小,從而決定猜的...