TypeError:只能将str(而不是“ set”)连接到str

时间:2019-06-27 13:15:18

标签: python python-3.x tkinter

基本上,我试图将在tkinter中制作的Entry box用作input,以将value传递给我的信号发生器。但是我得到标题中提到的错误。但是,如果我将value通过终端,则它可以正常工作,这可能是tkinter的问题,而不是乐器的问题(Rohde和Schwarz SMB100A)。

我尝试将值传递为string,正如错误所暗示的那样,但是没有运气。

import visa
import tkinter as tk


rm = visa.ResourceManager()
print(rm.list_resources())
inst = rm.open_resource('TCPIP::192.168.100.200::INSTR')

#This one would work, after i bind the function to the button,
#i just press it and it passes the preset value. 
#All i want to do is pass a value through the Entry widget, 
#instead of having a set one.
#freq = str(250000) 
#def freqset_smb100a():
    #inst.write("SOUR:FREQ:CW " + freq)

inst.write("OUTP ON")

def freqset_smb100a():
    inst.write(f"SOUR:FREQ:CW " + {str(input_var.get())})



HEIGHT = 400
WIDTH = 600

root = tk.Tk()

input_var = tk.StringVar()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg='#80c1ff', bd=5)
frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')

button = tk.Button(frame, text="Set Freq", font=40, command=freqset_smb100a)
button.place(relx=0.7, relheight=1, relwidth=0.3)

entry = tk.Entry(frame, font=15, textvariable=str(input_var.get))
entry.place(relx=0.35, relheight=1, relwidth=0.3)


root.mainloop()

这是我按button传递值时遇到的错误。

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\vrozakos\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/PyTests/Signal_gen_v2.py", line 19, in freqset_smb100a
    inst.write(f"SOUR:FREQ:CW " + {str(input_var.get())})
TypeError: can only concatenate str (not "set") to str

1 个答案:

答案 0 :(得分:2)

您的问题是,在f"SOUR:FREQ:CW " + {str(input_var.get())}中,{str(...)} set文字。它会按原样创建要尝试添加到字符串中的集合。

您要使用的格式化字符串就是

 print(f"SOUR:FREQ:CW {input_var.get()}")

也就是说,{}之间的任何内容都将被评估,转换为字符串并插入其中。

如果您的设备不支持较新的python版本,请删除字符串前面的f ,然后将其添加

write("SOUR:FREQ:CW" + str(input_var.get()))