【问题标题】:using entry.get in a list count in python在 python 的列表计数中使用 entry.get
【发布时间】:2022-01-16 01:47:53
【问题描述】:

我尝试使用 GUI 中的 ID 条目来计算 Excel 列中的相似 ID。

我总是在 if 循环和红色显示中得到 0。 但是列里有类似的ID。

我的代码

l1 = tk.Label(tab2, text="Status Check")
l1.place(x=10, y=10)
l2 = tk.Label(tab2, text="ID")
l2.place(x=10, y=60)

ID = tk.Entry(tab2)
ID.place(x=80, y=60)

l2 = tk.Label(tab2, text="Status")
l2.place(x=10, y=100)

t1 = tk.Entry(tab2)
t1.place(x=80, y=100)

comment = tk.Label(tab2)
comment.place(x=240, y=100)

df = pd.read_excel(r'Excel.xlsx')
IDlist = df['ID'].tolist()
id = ID.get()

def immunity_check():
    d = IDlist.count(id)
    print(d)

    if d >= 2:
        t1.config(bg= "Green")
        comment.configure(text="Fully vaccinated!")
    elif d == 1:
        t1.config(bg= "Yellow")
        comment.configure(text="Vaccinated!")
    else d <= 0:
        t1.config(bg= "Red")
        comment.configure(text="Not vaccinated!")

任何人都可以就如何修复它提供建议吗?

【问题讨论】:

  • 如何运行这段代码?通常的问题是Entry 不像input() 那样工作 - 它不会等待您的数据,但它只会通知 tkinter 它应该在窗口中显示什么小部件。如果您在 Entry() 之后直接运行 .get() ,那么您会在它显示在 window 之前以及在此窗口中将任何数据放入 Entry 之前获得值。将数据放入Entry 后,您应该有一些使用 .get()` 运行功能的按钮
  • 我有一个按钮来运行函数button = tk.Button(tab2,text="Check",command=immunity_check) button.place(x=10,y=180)
  • 我在你的问题中没有看到这个功能。我无法读懂你的想法。你必须显示所有有问题的细节。如果您有新信息,那么最好在问题中显示(不在评论中) - 它会更具可读性,更多人可能会看到它。此时我只看到ID.get() 不在功能中 - 所以它在Entry 为空时在开始时执行。你必须在函数内部运行它。

标签: python excel pandas tkinter


【解决方案1】:

我完全同意furas comment。谢谢他,他解决了。

问题

目前,代码正在按下按钮之前从您的文本字段中读取输入。在ID.get() 语句和观察控制台后面放置一个print(id),例如:

# GUI initialization omitted for brevity

df = pd.read_excel(r'Excel.xlsx') # read from Excel before button-pressed
IDlist = df['ID'].tolist()

id = ID.get() # get input from text-field before button-pressed
print(id)

# wait for a button press

# below is called on button-press and uses previously read id as argument
def immunity_check():

解决方案

这就是你可以解决的方法。 id 应该在按下按钮后从文本输入中读取。所以将 move 语句放入方法中:

# part 1:  GUI initialization omitted for brevity

# part 2:  define functions to call later
def read_ids():
    df = pd.read_excel(r'Excel.xlsx')
    return df['ID'].tolist()

def immunity_check():
    id = ID.get()  # read the id to search/count
    d = id_list.count(id)
    print(f"occurrences of id '{id}' in list: {d}")

    if d >= 2:
        t1.config(bg= "Green")
        comment.configure(text="Fully vaccinated!")
    elif d == 1:
        t1.config(bg= "Yellow")
        comment.configure(text="Vaccinated!")
    else d <= 0:
        t1.config(bg= "Red")
        comment.configure(text="Not vaccinated!")

# part 3: main starts
id_list = read_ids()

# add button with trigger to function immunity_check()
button = tk.Button(tab2,text="Check",command=immunity_check) button.place(x=10,y=180)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多