How to pass a textbox entry to variables using tki

2019-07-30 17:20发布

问题:

I have some fairly simple code to get values for a urlstring.

I have looked at all the other questions and cant seem to find a relevant answer I can apply

Some of the code comes up first in the Ipython console which I expect and will change later and I do get a value in Ipython console from the hardcoded variables on button press but cant seem to get value of text boxes into the variables and then use them instead?

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

But for the life of me I cant get the variables from the textboxes into the variables cur1_1 and cur2_1 and am getting the typeerror.

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

When I change it to string it says must be 3 digit long I would have thought It would have been a bit simpler than this. Any help please?

Also once I have the returned values for the exchange rates I need them to be converted to a decimal to 9 places and displayed with commas for monetary use .

Full code here https://pastebin.com/uPWyPXMZ

回答1:

Your problem seems to be you're using cur1_1 and cur2_1 as if they were strings when you should be calling their StringVar.get() methods to access their string values.

A simple-minded example:

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()

Put text in the entry box, and click the button. The text will be transfered from the entry box to the label via the .get() method of the StringVar associated with the Entry when it was created.