【问题标题】:how to assign the variable for python tkinter entry?如何为 python tkinter 条目分配变量?
【发布时间】:2021-10-21 13:26:59
【问题描述】:

我正在尝试从 Tkinter 创建一个简单的“SOS”益智游戏。我正在使用 grid 方法创建一个 entry widgets 网格。现在我想要一个 assigned variables 为每个条目。我尝试使用 for 循环来做到这一点,但我不能以正确的方式使用该变量。你能帮助我吗?我的问题想法解释如下图,

代码

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

【问题讨论】:

  • 您不想要单个变量,您想要一个容纳所有变量的容器。可以是 25 元素列表,可以是 5 元素列表的 5 元素列表,也可以是键为(行、列)元组的字典。

标签: python python-3.x tkinter


【解决方案1】:

您应该将制作的小部件存储到列表或字典中,而不是在旅途中创建变量。该列表似乎更合理,因为您可以更轻松地对其进行索引。

下面是一个简单但完整的示例,展示了如何制作二维列表以及在该列表中搜索条目对象:

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()

您必须输入一些行和列,例如0,0,它指的是第一行第一列,然后按下按钮。确保条目中没有空格。您不应该太担心搜索部分,因为您可能需要一些其他逻辑。但是,您应该使用这种方法并将其存储在容器中,而不是在旅途中制作变量。

另外请注意,您不必使用textvariable,因为这里完全不需要这些。你可以对Entry 本身的原始对象做任何你想做的事情。只需确保列表索引从 0 而不是 1 开始(或从给定的正常值中减去 1)。

【讨论】:

  • 非常感谢。
  • @DilshanMadhuranga 如果它解决了您的问题,请务必标记为正确答案:)
  • 好的。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2017-05-15
  • 2018-08-23
  • 1970-01-01
  • 2012-07-31
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多