特定循环中的Tkinter标签文本重叠

时间:2018-05-17 20:50:06

标签: python python-3.x user-interface tkinter

我在"简单"使用Python和Tkinter搜索界面。以下是我所得到的一些示例代码:

#!/usr/bin/env/python

from tkinter import *
import os
import csv
import sys

def fetch()

    word = e1.get()
    definitions = []

    with open(file) as db:
        dbreader = csv.reader(db, delimiter="\t")
        for row in dbreader:
            if word in row[1]:
                definitions.append(row[4])

    if not definitions:
        output_string = word + " not in database"

    else:
        output_string = "Found " + word

    result_out = Label(master)
    result_out.config(text=output_string)
    result_out = result_out.grid(row=3, column = 0)

master = Tk()

word_entry = Label(master, text = "word")
word_entry.grid(row=0, column = 0)

e1 = Entry(master)

e1.grid(row=0, column=1)

Button(master, text='Search', command=fetch).grid(row=2, column=1, sticky=(N, S, W, E), pady=4)

mainloop()

如果我搜索数据库中找到的单词,代码将按预期运行。如果我搜索一个不在数据库中的单词,我下一个带有单词的搜索将与之前的输出重叠。反之亦然,如果我只搜索数据库中找不到的项目,标签将按预期刷新。当这些循环"交替"我遇到了问题。世界上到底发生了什么?

1 个答案:

答案 0 :(得分:1)

每次拨打fetch()时,是否要从文件加载dafinition?我想不是。我把定义放在函数之外。此外,不是从文件中加载定义,而是仅为测试目的定义一组随机奶酪。

为每个问题创建一个新的result_out标签,@ Paul Cornelius指出。最好为标签指定textvariable并使用它来更改文本。因此,也要在函数外部创建此标签。

from tkinter import *

definitions = ['Stilton','Cheshire','Tilsit','Brie'] # Instead of file read

def fetch():
    word = e1.get()
    if not (word in definitions):
        output_string = word + " not in database"
    else:
        output_string = "Found " + word
    query.set(output_string) # Set result_out to output_string

master = Tk()

word_entry = Label(master, text = "word")
word_entry.grid(row=0, column = 0)

e1 = Entry(master)
e1.grid(row=0, column=1)

query = StringVar() # Use StringVar to interact with result_out
result_out = Label(master, textvariable=query)
result_out = result_out.grid(row=3, column = 0)

Button(master, text='Search', command=fetch).grid(row=2, column=1,
                                                  sticky=(N, S, W, E), pady=4)

mainloop()