繁体   English   中英

如何在python中使用tkinter将文本框条目传递给变量

[英]How to pass a textbox entry to variables using tkinter in python

我有一些相当简单的代码来获取urlstring的值。

我查看了所有其他问题,但似乎找不到可以适用的相关答案

一些代码首先在Ipython控制台中出现,我期望它会在以后更改,并且确实在Ipython控制台中从按钮按下时的硬编码变量中获取了一个值,但似乎无法将文本框的值添加到变量中,然后使用它们代替?

amount = '1'
cur1 = input('What Currency would you like to trade from? ')
cur2 = input('What Currency would you like to trade to? ')
cur1_1 = StringVar()
cur2_1 = StringVar()
#i = 0 


#Textboxes for user input
txtcur1 = Entry(root, font="Helvetica 11 bold",bg="white", width=6, textvariable=cur1_1)
txtcur1.place(x=110, y=50)
txtcur2 = Entry(root, font="Helvetica 11 bold",bg="white", width=6, textvariable=cur2_1)
txtcur2.place(x=110, y=75)
#End


def results():
    t = datetime.utcnow()  
    url1  = "http://www.xe.com/currencyconverter/convert/" + "?Amount=" + amount + "&From=" + cur1 + "&To=" + cur2
    url2 = "http://www.xe.com/currencyconverter/convert/" + "?Amount=" + amount + "&From=" + cur2_1 + "&To=" + cur1_1

但是对于我一生,我无法将文本框中的变量放入变量cur1_1cur2_1并且遇到了typeerror。

url2 = "http://www.xe.com/currencyconverter/convert/" + "?Amount=" + amount + "&From=" + cur2_1 + "&To=" + cur1_1
TypeError: must be str, not StringVar

当我将其更改为字符串时,它说必须是3位数字长,我以为这会比这简单一些。 有什么帮助吗?

同样,一旦获得了汇率的返回值,我就需要将它们转换为decimal to 9decimal to 9并显示逗号以供货币使用。

完整代码在这里https://pastebin.com/uPWyPXMZ

您的问题似乎是您在使用cur1_1cur2_1好像它们是字符串一样,所以您应该调用它们的StringVar.get()方法来访问它们的字符串值。

一个简单的例子:

import tkinter as tk

def show_text():
    label_text.set('Heh, heh, heh, you said, "' + entry_text.get() + '"')

root = tk.Tk()

entry_text = tk.StringVar()
entry = tk.Entry(root, width=10, textvariable=entry_text)
entry.pack()

button = tk.Button(root, text="Click Me", command=show_text)
button.pack()

label_text = tk.StringVar()
label = tk.Label(root, textvariable=label_text)
label.pack()

root.mainloop()

在输入框中输入文本,然后单击按钮。 文本将在创建时通过与Entry关联的StringVar.get()方法从输入框传输到标签。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM