![](/img/trans.png)
[英]How to retrieve the contents of entry and text widget and assign it to a variable in tkinter using python
[英]how to assign the variable for python tkinter entry?
我正在嘗試從 Tkinter 創建一個簡單的“SOS”益智游戲。 我正在使用 grid 方法創建一個條目小部件網格。 現在我想要為每個條目分配一個變量。 我嘗試使用 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
您應該將制作的小部件存儲到列表或字典中,而不是隨時隨地創建變量。 該列表似乎更合理,因為您可以更輕松地對其進行索引。
下面是一個簡單但完整的示例,展示了如何制作二維列表以及在此列表中搜索條目對象:
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)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.