【问题标题】:How would I implement a guessing game with tkinter using things like input boxes and if statements我将如何使用输入框和 if 语句之类的 tkinter 实现猜谜游戏
【发布时间】:2019-07-16 20:32:17
【问题描述】:

我需要帮助将我创建的猜谜游戏与我的 Tkinter GUI 结合起来。我主要需要关于如何在 Tkinter 中使用 if 语句以及如何改进我的 GUI 代码的帮助,因为我觉得它可以变得更简单。

提前谢谢你。

Tkinter 图形用户界面

from tkinter import *


#key function
def click():
    entered_text=textentry.get()
    output.delete(0.0, END)
    

#main:
window = Tk()
window.title("Guessing Game")
window.configure(background="lightskyblue1")

#BackgroundPhoto:
photo1 = PhotoImage(file="guessinggame.gif")
Label (window, image=photo1, bg="black") .grid(row=0, column=0, sticky=W)

#Label.1
Label (window, text="Enter your guess:", bg="lightskyblue1", fg="black", font="none 12 bold") .grid(row=1, column=0, sticky=W)

#InputBox
textentry = Entry(window, width=20, bg="white")
textentry.grid(row=2, column=0, sticky=W)

#CheckButton
Button(window, text="CHECK", width=6, command=click) .grid(row=3, column=0, sticky=W)

#Label.2
Label (window, text="Your guess was:", bg="lightskyblue1", fg="black", font="none 12 bold") .grid(row=4, column=0, sticky=W)

#OutputBox
output = Text(window, width=5, height=1, wrap=WORD, background="lightskyblue1")
output.grid(row=5, column=0, columnspan=2, stick=W)

#mainloopRunner
window.mainloop()

猜谜游戏

import random
affirmations = ('y', 'yeah', 'yes', 'yep', 'yup', 'sure')
print('I am thinking of a number from 1 to 10. Guess which one.')
number = random.randint(1, 10)
guesses = 1
while True:
    guess = int(input('Choose a number between 1 and 10: '))
    if guess == number:
        print('Wow, you got it after only {} guesses.'.format(guesses))
        play_again = input('Want to play again? [Y/N] ')
        if play_again.lower() in affirmations:
            guesses = 0 
            number = random.randint(1, 10) 
        else:
            print('Thanks for playing.')
            break
    elif 10 < guess < 1:
        print('Only guesses between 1 and 10, please.')
    elif guess < number:
        print('Think higher...')
    else:
        print('Go lower...')
    guesses += 1

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    将 while 循环中的代码放入 click() 函数中的原始程序中,并进行一些更改。由于click() 是一个函数,您需要将变量guesses 设为全局变量。

    def click():
        global guesses
    

    为了与用户交流,您使用文本区域而不是打印。在输入新文本之前清除文本区域:

    output.delete(0.0, END)             # Clear ouytout text area
    output.insert('1.0', 'A message!')  # Display in text area
    

    否则,您照常使用if。

    关于 GUI 代码,我看不出有任何明显的方法可以使它更简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 2018-02-07
      • 2018-12-05
      • 1970-01-01
      • 2015-04-18
      • 2019-01-20
      • 1970-01-01
      相关资源
      最近更新 更多