简体   繁体   English

为 tkinter python 中的输入框设置隐藏字符串值

[英]Set a hidden string value to an entry box in tkinter python

I'm trying to make my own spin on Hangman.我正在尝试对 Hangman 进行自己的调整。 A basic part of Hangman is that the user guesses a letter and if it is there, it appears in the entry box else it gets added to a list of incorrect guesses. Hangman 的一个基本部分是用户猜测一个字母,如果它在那里,它会出现在输入框中,否则它会被添加到错误猜测列表中。

What I want to do now is assign a letter to each read-only entry box based on the random word generated.我现在要做的是根据生成的随机单词为每个只读输入框分配一个字母。 However, I also don't want the user to know what letter is assigned to it (obviously).但是,我也不希望用户知道分配给它的字母(显然)。

def press(num):
    string1 = " "
    string1+=str(num)
    appears.set(string1)

appears = StringVar()
entrybox = Entry(hangman,state= 'readonly',textvariable = appears)
entrybox.place(x = 0, y = 0)

q = Button(hangman, text = 'Q', width = 4, command = lambda : press('Q'))
q.place(x = 200, y = 440)

This is what i've managed to do so far这就是我到目前为止所做的

You can use a dictionary to store a mapping from letters to StringVars.您可以使用字典来存储从字母到 StringVars 的映射。 Then, look up the guessed letter and replace the text from a placeholder to the letter.然后,查找猜测的字母并将占位符中的文本替换为该字母。

word = "tiger" # just an example

let2svar = {}

for let in word:
  svar = StringVar()
  svar.set("_")
  entrybox = Entry(hangman, state='readonly', textvariable=svar)
  entrybox.place(x=0, y=0)
  if let not in let2svar:
    let2svar[let] = []

  let2svar[let].append(svar)


# Now when user guesses letter 'guess', check if it is in the word.

if guess in let2svar:
  for svar in let2svar[guess]:
    svar.set(guess)

You can also check out https://docs.python.org/3/library/collections.html#collections.defaultdict for a cleaner way to handle the dictionary.您还可以查看https://docs.python.org/3/library/collections.html#collections.defaultdict以更简洁地处理字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM