关于python:in< string>’

in <string>' requires string as left operand, not StringVar

我正在尝试使用self.search来确定.txt文件中哪些行将被复制,即:条目为"蓝色",它将在文本中打印所有蓝色的行。每个按钮搜索不同的.txt文件。

Exception in Tkinter callback Traceback (most recent call last): File"C:\Users\gblmac\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 1702, in call return self.func(*args) File"D:\Users\gblmac\Desktop\Python programs\Testing\GUI class and init.py", line 37, in searchvision if self.usertext in line: TypeError: 'in ' requires string as left operand, not StringVar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from tkinter import *

class App:
    def __init__(self):
        self.master = Tk()
        self.master.title("PM and Vision Finder")
        self.master.configure(bg="orange")
        self.master.geometry("500x500")
        self.mybutton1 = Button(self.master, text="Vision Names", command=self.searchvision)

        self.mybutton1.grid(row=0, column=0)

        self.mybutton2 = Button(self.master, text="PM",
                           command=self.searchpm)

        self.mybutton2.grid(row=1, column=0)

        self.usertext = StringVar()
        self.initialtext = StringVar()
        self.initialtext.set ("Type Here")

        self.myentry = Entry(self.master, textvariable=self.initialtext)
        self.myentry.grid(row=2, column=0)

    def searchvision(self):

        self.search = open(r"D:\Users\gblmac\Desktop\Python programs\Vision Names\Vision Names.txt")
        for line in self.search:
            if self.usertext in line:
                print (line)

    def searchpm(self):

        self.search = open(r"D:\Users\gblmac\Desktop\Python programs\PMs\PMs.txt")
        for line in self.search:
            if self.usertext in line:
                print (line)

        print (self.usertext.get())


    self.master.mainloop()

App()

in requires string as left operand

为此

1
if self.usertext in line:

not StringVar

因为左边的变量是stringvar

1
self.usertext = StringVar()

你需要使用

1
if self.usertext.get() in line: