[英]how to assign the variable for python tkinter entry?
I am trying to create a simple 'SOS' puzzle game from Tkinter.我正在尝试从 Tkinter 创建一个简单的“SOS”益智游戏。 I am creating an entry widgets grid using the grid method.
我正在使用 grid 方法创建一个条目小部件网格。 Now I want an assigned variables for each entry.
现在我想要为每个条目分配一个变量。 I try to do it using for loops but I can't use that variable the proper way.
我尝试使用 for 循环来执行此操作,但无法以正确的方式使用该变量。 Can you help me?
你能帮助我吗? My question idea explain given below digram,
我的问题想法解释如下图,
Code代码
for i in range(5):
for j in range(5):
self.entry=Entry(root,textvariable=f'{i}{j}')
self.entry.grid(row=i,column=j)
self.position.update({f"{i}-{j}":f"{i}{j}"})
enter code here
Instead of creating variables on the go, you should store the widgets made into a list or a dictionary.您应该将制作的小部件存储到列表或字典中,而不是随时随地创建变量。 The list seems more reasonable as you can index it more easily.
该列表似乎更合理,因为您可以更轻松地对其进行索引。
Below is a simple, but full example that shows how you can make a 2-D list as well as search this list for the entry object:下面是一个简单但完整的示例,展示了如何制作二维列表以及在此列表中搜索条目对象:
from tkinter import * # You might want to use import tkinter as tk
root = Tk()
def searcher():
row = int(search.get().split(',')[0]) # Parse the row out of the input given
col = int(search.get().split(',')[1]) # Similarly, parse the column
obj = lst[row][col] # Index the list with the given values
print(obj.get()) # Use the get() to access its value.
lst = []
for i in range(5):
tmp = [] # Sub list for the main list
for j in range(5):
ent = Entry(root)
ent.grid(row=i,column=j)
tmp.append(ent)
lst.append(tmp)
search = Entry(root)
search.grid(row=99,column=0,pady=10) # Place this at the end
Button(root,text='Search',command=searcher).grid(row=100,column=0)
root.mainloop()
You have to enter some row and column like 0,0
which refers to 1st row, 1st column and press the button.您必须输入一些行和列,例如
0,0
,它指的是第一行、第一列,然后按下按钮。 Make sure there are no spaces in the entry.确保条目中没有空格。 You should not worry much about the searching part, as you might require some other logic.
您不必太担心搜索部分,因为您可能需要其他一些逻辑。 But instead of making variables on the go, you should use this approach and store it in a container.
但是不要在旅途中创建变量,您应该使用这种方法并将其存储在容器中。
Also a note, you do not have to use textvariable
as here the need of those are totally none.另请注意,您不必使用
textvariable
因为这里完全不需要这些。 You can do whatever you want with the original object of Entry
itself.您可以对
Entry
本身的原始对象做任何您想做的事情。 Just make sure you have the list indexing start from 0 rather than 1(or subtract 1 from the given normal values).只需确保列表索引从 0 开始,而不是从 1 开始(或从给定的正常值中减去 1)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.