简体   繁体   English

货币转换器中的tk输入和Optionmenu小部件出现问题

[英]Problems with tk entry and optionmenu widget in currency converter

I am currently having problems with my currency converter program in my python class. 我目前在python类中的货币转换器程序遇到问题。 I am trying to convert an amount, the entry widget, from the starting currency, the first option menu, to the desired currency, the second option menu. 我正在尝试将金额(输入小部件)从起始货币,第一个选项菜单转换为所需货币,第二个选项菜单。 I have spent hours reading the documentation, so I hope you can give me some input! 我已经花了数小时阅读文档,所以希望您能给我一些意见! Currently I only have two currencies in my list too so it will be easier to test. 目前,我的清单中也只有两种货币,因此测试起来会更容易。 The desired outcome would be a dynamic program that will be able to read the amount, currency 1, and currency 2 once the convert button is clicked. 期望的结果将是一个动态程序,一旦单击转换按钮,该程序将能够读取金额,货币1和货币2。 Here is my code: 这是我的代码:

# Module imports
import Tkinter as tk
import tkMessageBox

# Function Definitions
class Application(tk.Frame):

    def __init__(self, parent = None):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.setupUI()
        self.createWidgets()

    def setupUI(self):
        self.parent.title("User Input")
        self.grid()
        self.centerWindow()

    def centerWindow(self):
        app_width = 307
        app_height = 350

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - app_width)/2
        y = (sh - app_height)/2
        self.parent.geometry('%dx%d+%d+%d' % (app_width, app_height, x, y))

    def createWidgets(self):
        self.emptyFrame = tk.Frame(self.parent,bg="white")
        self.emptyFrame.grid(row=0,column=0,sticky="news")
        self.parent.grid_columnconfigure(0,weight=1)
        self.parent.grid_rowconfigure(0,weight=1)

        self.label1 = tk.Label(self.emptyFrame,text="Currency Converter",bg="white",font="Arial 26")
        self.label1.grid(row=0,column=0, sticky="news")
        self.label2 = tk.Label(self.emptyFrame,text="Visit http://www.xe.com/iso4217.php\nFor Currency Code Information",bg="white",font="Arial 8")
        self.label2.grid(row=0,column=0, sticky="news")
        self.label2.place(x = 55, y = 40)

        currAmount1 = tk.StringVar()                                    # Adding user imput for what value they want to convert
        self.currEntry1 = tk.Entry(self.parent, textvariable=currAmount1,bd=2,width=28,background="white")
        self.currEntry1.grid()
        self.currEntry1.place(x = 27, y = 125)


        currAmount2 = tk.StringVar()
        self.currEntry2 = tk.Entry(self.parent,textvariable=currAmount2,bd=2,width=28,background="white")
        self.currEntry2.grid()
        self.currEntry2.place(x = 27, y = 195)

        self.currency_list1 = ['USD','GBP'] #Creating the Currency Options menu and adding a list for all the currencies
        self.curr_start1 = tk.StringVar()
        self.curr_start1.set(self.currency_list1[0])
        self.currencyMenu1 = tk.OptionMenu(self.parent, self.curr_start1, *self.currency_list1)
        self.currencyMenu1.grid(row=0,column=0)
        self.currencyMenu1.place(x = 230, y = 120)


        self.currency_list2 = ['USD','GBP'] #Creating the Currency Options menu and adding a list for all the currencies
        self.curr_start2 = tk.StringVar()
        self.curr_start2.set(self.currency_list2[0])
        self.currencyMenu2 = tk.OptionMenu(self.parent, self.curr_start2, *self.currency_list2)
        self.currencyMenu2.grid(row=0,column=0)
        self.currencyMenu2.place(x = 230, y = 190)


        self.convertBtn = tk.Button(self.parent, text="Convert", font="Times 12", command=self.curr_search)
        self.convertBtn.grid()
        self.convertBtn.place(x = 120,y = 225)

    def curr_search(self):
        cur1 = self.curr_start1
        cur2 = self.curr_start2
        amount = currAmount1
        url = 'https://www.google.com/finance/converter?' 
        final_url = url + 'a=' + str(amount) + '&from=' + str(cur1) + '&to=' + str(cur2) # Adds the paramters the user inputs to the general url for converting to currencies
        web_obj = urllib2.urlopen(final_url) 
        results_str = str(web_obj.read())
        final_str = re.search('class=bld>(.+?)</span>',results_str).group(1) # Extracts the string between the class and </span> which is the final conversion
        final_num = map(int, re.findall(r'\d+', final_str)) # Extracts the integers from the final_str so that it wouldn't have the currency code in the final. Puts in a list
        final = str(final_num[0]) + '.' + str(final_num[1]) # Adds the decimal back from 
        web_obj.close()    
        return final

# Main body
root = tk.Tk()
root.resizable(width=False, height=False)
app = Application(root)
root.mainloop()

My answer didn't satisfy me so I solved your problem. 我的回答使我不满意,所以我解决了您的问题。 Changes: 变化:

  1. Added self keyword to currAmount1 , currAmount2 , and reflected this change everywhere in the script. currAmount1currAmount2添加了self关键字,并在脚本的各处反映了此更改。 ( currAmount1 -> self.currAmount1 ) currAmount1 > self.currAmount1

  2. Called .get() on the Tkinter variables at the start of curr_search() : curr_search()开始时在Tkinter变量上调用.get() curr_search()

     cur1 = self.curr_start1.get() cur2 = self.curr_start2.get() amount = self.currAmount1.get() 
  3. Instead of opening the whole web_obj file into a variable (which doesn't work), I read through the file line by line and called the reg expression search on every line. 我没有将整个web_obj文件打开到一个变量中(这不起作用),而是逐行读取文件并在每一行中调用reg表达式搜索。 When the search produces the result we expect (anything but None ), I store this result in final_str. 当搜索产生我们期望的结果(除None任何东西)时,我将此结果存储在final_str中。

  4. Added a check at the end of the file: If the map returns an integer value (for example, converting 1USD to USD will return 1), I only take the first element of the map, or else I use the expression you had in place. 在文件末尾添加了一个检查:如果map返回一个整数值(例如,将1USD转换为USD将返回1),那么我只会使用地图的第一个元素,否则我将使用您已有的表达式。

  5. Finally, I implement a way of showing the result: 最后,我实现了一种显示结果的方式:

     self.currEntry2.delete(0, tk.END) self.currEntry2.insert(tk.END, final) 

    Which will show the result in the second entry field. 它将在第二个输入字段中显示结果。

Here's the final code: 这是最终代码:

# Module imports
import Tkinter as tk
import tkMessageBox
import urllib2
import re

# Function Definitions
class Application(tk.Frame):

    def __init__(self, parent = None):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.setupUI()
        self.createWidgets()

    def setupUI(self):
        self.parent.title("User Input")
        self.grid()
        self.centerWindow()

    def centerWindow(self):
        app_width = 307
        app_height = 350

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - app_width)/2
        y = (sh - app_height)/2
        self.parent.geometry('%dx%d+%d+%d' % (app_width, app_height, x, y))

    def createWidgets(self):
        self.emptyFrame = tk.Frame(self.parent,bg="white")
        self.emptyFrame.grid(row=0,column=0,sticky="news")
        self.parent.grid_columnconfigure(0,weight=1)
        self.parent.grid_rowconfigure(0,weight=1)

        self.label1 = tk.Label(self.emptyFrame,text="Currency Converter",bg="white",font="Arial 26")
        self.label1.grid(row=0,column=0, sticky="news")
        self.label2 = tk.Label(self.emptyFrame,text="Visit http://www.xe.com/iso4217.php\nFor Currency Code Information",bg="white",font="Arial 8")
        self.label2.grid(row=0,column=0, sticky="news")
        self.label2.place(x = 55, y = 40)

        self.currAmount1 = tk.StringVar()                                    # Adding user imput for what value they want to convert
        self.currEntry1 = tk.Entry(self.parent, textvariable=self.currAmount1,bd=2,width=28,background="white")
        self.currEntry1.grid()
        self.currEntry1.place(x = 27, y = 125)


        self.currAmount2 = tk.StringVar()
        self.currEntry2 = tk.Entry(self.parent,textvariable=self.currAmount2,bd=2,width=28,background="white")
        self.currEntry2.grid()
        self.currEntry2.place(x = 27, y = 195)

        self.currency_list1 = ['USD','GBP'] #Creating the Currency Options menu and adding a list for all the currencies
        self.curr_start1 = tk.StringVar()
        self.curr_start1.set(self.currency_list1[0])
        self.currencyMenu1 = tk.OptionMenu(self.parent, self.curr_start1, *self.currency_list1)
        self.currencyMenu1.grid(row=0,column=0)
        self.currencyMenu1.place(x = 230, y = 120)


        self.currency_list2 = ['USD','GBP'] #Creating the Currency Options menu and adding a list for all the currencies
        self.curr_start2 = tk.StringVar()
        self.curr_start2.set(self.currency_list2[0])
        self.currencyMenu2 = tk.OptionMenu(self.parent, self.curr_start2, *self.currency_list2)
        self.currencyMenu2.grid(row=0,column=0)
        self.currencyMenu2.place(x = 230, y = 190)


        self.convertBtn = tk.Button(self.parent, text="Convert", font="Times 12", command=self.curr_search)
        self.convertBtn.grid()
        self.convertBtn.place(x = 120,y = 225)

    def curr_search(self):
        cur1 = self.curr_start1.get()
        cur2 = self.curr_start2.get()
        amount = self.currAmount1.get()
        url = 'https://www.google.com/finance/converter?' 
        final_url = url + 'a=' + str(amount) + '&from=' + str(cur1) + '&to=' + str(cur2) # Adds the paramters the user inputs to the general url for converting to currencies
        web_obj = urllib2.urlopen(final_url) 

        #Read each line , check if reg expression is in

        for line in web_obj:
            line = line.replace('\n', '')
            line = re.search('class=bld>(.+?)</span>', line)
            if line is not None:
                final_str = line

        final_str = final_str.group(1) # Extracts the string between the class and </span> which is the final conversion
        final_num = map(int, re.findall(r'\d+', final_str)) # Extracts the integers from the final_str so that it wouldn't have the currency code in the final. Puts in a list

        #If number is a decimal number, group, else take integer
        if len(final_num) > 1:
            final = str(final_num[0]) + '.' + str(final_num[1]) # Adds the decimal back from 
        else:
            final = str(final_num[0])

        web_obj.close()
        self.currEntry2.delete(0, tk.END)
        self.currEntry2.insert(tk.END, final)   
        return final

# Main body
root = tk.Tk()
root.resizable(width=False, height=False)
app = Application(root)
root.mainloop()

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

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