【问题标题】:tkinter hangman Buttontkinter 刽子手按钮
【发布时间】:2014-04-04 20:35:56
【问题描述】:

我有 .txt 文件,其中包含我自己输入的单词,但该程序确实允许您输入自己的单词。问题似乎是,当我单击一个按钮时,它不会将其识别为对单词的猜测,我意识到这段代码还远未完成,但任何帮助将不胜感激如果您还可以让我知道如何在键盘上方输入字段,那就太好了:D

from tkinter import*

import time
import random

root= Tk()
top = Tk()


top.title('Hangmanz') 
top.geometry('500x140')

root.geometry('200x250')
root.title('Photo')




def appear(index, letter):
    # This line would be where you insert the letter in the textbox
    guess = ('')
    guess += str(letter)
    if letter in line:
        print(char,end=''),



    # set the players guess to guesses







    w.insert(0,letter)

    # Disable the button by index
    buttons[index].config(state="disabled")







letters=["Q", "A", "Z", "W", "S", "X", "E", "D", "C", "R", "F", "V", "T", "G", "B",
         "Y", "H", "N", "U", "J", "M", "I", "K", "O", "L", "P"]

# A collection (list) to hold the references to the buttons created below
buttons = []

for index in range(26): 
    n=letters[index]

    button = Button(top, bg="White", text=n, width=5, height=1, relief=GROOVE,
                    command=lambda index=index, n=n: appear(index, n))

    # Add the button to the window
    button.grid(padx=2, pady=2, row=index%3, column=index//3)

    # Add a reference to the button to 'buttons'
    buttons.append(button)

w = Entry(root,width=22, fg="black",
bg="#f2f2f2", font="Impact")
w.pack()



#photo   
canvas = Canvas(root,width = 200, height = 200, bg = 'white')
canvas.pack(expand = YES, fill = BOTH)
gif1 = PhotoImage(file = 'Scaffold01.gif')
canvas.create_image(50, 10, image = gif1, anchor = NW)

ok=True
while ok==True:
    answer = input ("Would you like to input a new word? Enter Y or N ")

    if answer == ('Y'):
        file = open("Hangmanwords.txt", "a")
        d =input("enter new word ")
        file.write("\n"+d)
        file.close()
        c=input("would you like to add another word? Y or N")
        if c == ('y'):
            ok=True
        elif c == ('N'):
            ok=False
    elif answer == ('N'):
            ok=False
time.sleep(1)
print("Get ready to play!")



line = random.choice(open("Hangmanwords.txt","r").readlines())
print(line)

for char in line:
        print("*")





root.mainloop()
top.mainloop()

【问题讨论】:

  • 这段代码有太多基本问题:你不应该使用inputTkinter,你不应该在GUI中调用time.sleep,你不应该有一个除了事件循环之外的无限循环,你不应该调用mainloop两次。

标签: python button tkinter


【解决方案1】:

由于我不太擅长 Python,我无法发现您的错误/如何修复它,但我可以回答您关于如何制作输入框的问题:

from tkinter import *
root=Tk()
root.geometry('400x400')
def receiveVar:
    x=var.get()
    #What you want to do with the variable goes here
var=StringVar()
mentry=Entry(root,textvariable=var).pack()
btn=Button(root,text='Ok',command=receiveVar).pack()
root.mainloop()

【讨论】:

  • 您创建了一个糟糕的示例:mentrybtn 将始终设置为 None——这是人们一直在此站点上询问的常见初学者错误。一个好的答案不应该犯这种常见的错误,因为它有助于传播一种糟糕的编程风格。
猜你喜欢
  • 1970-01-01
  • 2017-03-09
  • 2018-10-20
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2015-02-03
  • 1970-01-01
相关资源
最近更新 更多