Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |
 User Name: Password: Remember me

New Free Tools on Dev Shed!
We're Excited to announce that Dev Shed now has 70 free tools on the site. To learn more, click here!

 Dev Shed Forums Sponsor:
#1
June 5th, 2013, 12:59 PM
 Eddur
Registered User

Join Date: Jun 2013
Posts: 2
Time spent in forums: 12 m 18 sec
Reputation Power: 0
Tkinter Help!

Hey guys, so I'm working on a simple calculator project for Python (using Tkinter) and have encountered a problem which, try as I might, cannot solve. Here's the code so far.

Code:
```from tkinter import *

root = Tk()
root.geometry("30x130")

def explain():
print("This is a simple calculator interface which can add and subtract values \nup to 999.")

def fillDisplay(x):
EntryBox.insert(0, str(x))

def clearDisplay():
EntryBox.delete(0, END)

EntryBox = Entry(root, width=7)
EntryBox.grid(row=0, columnspan=3)

for x in range(7, 10):
Button(root, text=str(x), command=fillDisplay(x)).grid(row=1, column=(x-7), sticky=W)

for x in range(4, 7):
Button(root, text=str(x), command=fillDisplay(x)).grid(row=2, column=(x-4), sticky=W)

for x in range(1, 4):
Button(root, text=str(x), command=fillDisplay(x)).grid(row=3, column=(x-1), sticky=W)

Button(root, text="0", command=fillDisplay(0)).grid(row=4, sticky=W)
Button(root, text="+").grid(row=4, column=1, sticky=W)
Button(root, text="-").grid(row=4, column=2, sticky=W)

Button(root, text="=", width=4).grid(row=0, column=5, rowspan=2, columnspan=2, stick=S)
Button(root, text="Clear", height=2, command=clearDisplay).grid(row=2, column=5, rowspan=2, columnspan=2, stick=N)

mainloop()```

So it's a pretty simple interface, with just the digits 0-9 (as buttons), a plus button, a minus button, an equals button and a clear button. There's also an Entry widget to be used as a display.

The problem:
The buttons 0-9 aren't working. Instead of pasting the number they have on them to the display when clicked, they do it at startup (so the Entry box starts out with 321654987 in it). No idea what's happening, it might be something to do with the way I have set up the "fillDisplay" function.

#2
June 5th, 2013, 04:16 PM
 Schol-R-LEA
Commie Mutant Traitor

Join Date: Jun 2004
Location: Norcross, GA (again)
Posts: 1,798
Time spent in forums: 1 Month 2 Weeks 3 Days 1 h 39 m 19 sec
Reputation Power: 1569
The primary cause of the problem is that the command option for the Button class c'tor expects a function or method, which would have to be passed without its argument list:

Code:
`    Button(root, text=str(x), command=fillDisplay).grid(row=1, column=(x-7), sticky=W)`

Unfortunately, this presents a different problem, in that the callback cannot take an argument, but the fillDisplay() function expects one. There is no way to pass the value to fillDisplay() as it is now defined.

The solution - a bit heavyweight, but nonetheless workable - is to define a subclass of the Button class, which should pass one of its methods as the callback.

Code:
``` class NumberButton(Button):
def __init__(self, parent, number, display):
Button.__init__(self, parent, text=number, command=self.fillDisplay)
self.value = number
self.display = display
def fillDisplay(self):
self.display.insert(0, str(self.value))```

Note that, in order to have the declaration of the new class as general as possible, I have both the parent window and the Entry box passed as arguments to the c'tor.

Now, this is all well and good, except that it inserts the values in the wrong order. A bit of string-shuffling will fix that, however. Below is a complete working version of your code.

Python Code:
 Original - Python Code
```from tkinter import *import tkinter.messagebox as mb class NumberButton(Button):    def __init__(self, parent, number, display):        Button.__init__(self, parent, text=number, command=self.fillDisplay)        self.value = number        self.display = display     def fillDisplay(self):        curr_value = self.display.get()        if curr_value == '0':            new_value = str(self.value)        else:            new_value = ''.join([curr_value, str(self.value)])        self.display.delete(0, END)        self.display.insert(0, new_value) def explain():    mb.showinfo("About", "This is a simple calculator interface which can add and subtract values \nup to 999.", icon=mb.INFO)  def clearDisplay():    EntryBox.delete(0, END)    EntryBox.insert(0, '0')    root = Tk()root.geometry("175x140")root.title = "Calculator" menubar = Menu(root)menubar.add_command(label="About", command=explain) EntryBox = Entry(root, justify=RIGHT, width=7)EntryBox.grid(row=0, columnspan=3)EntryBox.insert(0, '0') # store a reference to the NumberButtons in a dictionary indexed on the # value of the buttonnumber = dict()number[0] = NumberButton(root, 0, EntryBox).grid(row=4, sticky=W)for x in range(7, 10):    number[x] = NumberButton(root, x, EntryBox).grid(row=1, column=(x-7), sticky=W) for x in range(4, 7):    number[x] = NumberButton(root, x, EntryBox).grid(row=2, column=(x-4), sticky=W) for x in range(1, 4):    number[x] = NumberButton(root, x, EntryBox).grid(row=3, column=(x-1), sticky=W)  Button(root, text="+").grid(row=4, column=1, sticky=W)Button(root, text="-").grid(row=4, column=2, sticky=W) Button(root, text="=", width=4).grid(row=0, column=5, rowspan=2, columnspan=2, stick=S)Button(root, text="Clear", height=2, command=clearDisplay).grid(row=2, column=5, rowspan=2, columnspan=2, stick=N) root.config(menu=menubar) mainloop()
```
__________________
Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
#define KINSEY (rand() % 7) λ Scheme is the Red Pill
Scheme in ShortUnderstanding the C/C++ Preprocessor
Taming PythonA Highly Opinionated Review of Programming Languages for the Novice, v1.1

FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. \$4500 obo. tverres@et.ins.gov

#3
June 5th, 2013, 05:12 PM
 Eddur
Registered User

Join Date: Jun 2013
Posts: 2
Time spent in forums: 12 m 18 sec
Reputation Power: 0
Wow, that was... amazing. Detailed, informative, just amazing man. You explained everything so that a noob like me could understand. ^^

Thanks a bunch!

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Tkinter Help!

## Developer Shed Advertisers and Affiliates

 Thread Tools Search this Thread Search this Thread: Advanced Search Display Modes Rate This Thread Linear Mode Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts vB code is On Smilies are On [IMG] code is On HTML code is Off
 View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox Forum Jump Please select one User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home -------------------- Programming Languages    PHP Development        PHP FAQs and Stickies    Perl Programming        Perl FAQs and Stickies    C Programming        C Programming FAQs and Stickies    Java Help        Java FAQs    Python Programming        Python Programming FAQs    Ruby Programming        Ruby Programming FAQs    Game Development        Game Development FAQs Programming Languages - More    ASP Programming        ASP Programming FAQs    .Net Development        .Net Development FAQs    Visual Basic Programming        Visual Basic Programming FAQs    Software Design        Software Design FAQs    ColdFusion Development        ColdFusion Development FAQs    Delphi Programming        Delphi Programming FAQs    Regex Programming        Regex Programming FAQs    XML Programming        XML Programming FAQs    Other Programming Languages        Other Programming Languages FAQs Web Design    HTML Programming        HTML Programming FAQs    JavaScript Development        JavaScript Development FAQs    CSS Help        CSS Help FAQs    Flash Help        Flash Help FAQs    Photoshop Help        Photoshop Help FAQs    Web Design Help        Web Design Help FAQs    Website Critiques        Website Critiques FAQs    Search Engine Optimization        Search Engine Optimization FAQs Mobile Programming    Mobile Programming        Mobile Programming FAQs    iPhone SDK Development        iPhone SDK Development FAQs    Android Development        Android Development FAQs    BlackBerry Development        BlackBerry Development FAQs Web Site Management    Business Help        Business Help FAQs    Development Software        Development Software FAQs    Scripts        Scripts FAQs Databases    Database Management        Database Management FAQs    DB2 Development        DB2 Development FAQs    MySQL Help        MySQL Help FAQs    PostgreSQL Help        PostgreSQL Help FAQs    Firebird SQL Development        Firebird SQL Development FAQs    MS SQL Development        MS SQL Development FAQs    Oracle Development        Oracle Development FAQs    LDAP Programming        LDAP Programming FAQs System Administration    Mail Server Help        Mail Server Help FAQs    Apache Development        Apache Development FAQs    Security and Cryptography        Security and Cryptography FAQs    Antivirus Protection        Antivirus Protection FAQs    DNS        DNS FAQs    IIS        IIS FAQs    Networking Help        Networking Help FAQs    FTP Help        FTP Help FAQs Operating Systems    BSD Help        BSD Help FAQs    Linux Help        Linux Help FAQs    UNIX Help        UNIX Help FAQs    Windows Help        Windows Help FAQs    Mac Help        Mac Help FAQs Web Hosting    Web Hosting        Web Hosting FAQs    Free Web Hosting        Free Web Hosting FAQs    Web Hosting Requests        Web Hosting Requests FAQs    Web Hosting Offers        Web Hosting Offers FAQs Computer Hardware    Computer Hardware    CPUs        CPUs FAQs    Cooling        Cooling FAQs    Embedded Programming        Embedded Programming FAQs    Motherboards        Motherboards FAQs    Multimedia Hardware        Multimedia Hardware FAQs Other    Dev Shed Lounge        Dev Shed Lounge FAQs    Development Articles        Development Articles FAQs    Beginner Programming        Beginner Programming FAQs    Hire A Programmer        Hire A Programmer FAQs    Project Help Wanted        Project Help Wanted FAQs Latest News Updated Hourly    Technology News    Business News    Science News Forum Information    Forum Rules/Guidelines        Forum Rules/Guidelines FAQs    Forum Announcements        Forum Announcements FAQs    Dev Shed Gaming Center        Go to the Dev Shed Battle Arena        Go to the Dev Shed Arcade Games        Go to the Legend of the Green Dragon    Suggestions & Feedback        Suggestions & Feedback FAQs

 Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |