Hello,
I have been following discussions and codes for a while on Daniweb, and I'm really interested in this amazing community. I just joined though.

I'm facing a problem in my Tk inter task.
I have a code and I need to make a TKinter interface that does the job instead of having a normal interface.

I would really appreciate some help regarding this issue and any kind of help/comment/support/advice is appreciated :)

I'm REALLY VERY new to tkinter, as I have learned how to code, but still new to put it in a GUI style.

this is my code ..

## Taiki
## this is a vending machine
## there is two kinds of users, 1. Admin 2. buyer.
## I'm using three classes as I decided to practice classes and inheri.
## Vending Machine 2011

class Coin(object):
    def __init__(self,denom,value):
        self.Denomination = "CENTS"
        self.Value = 0
        if value == 25 or value == 50:
            self.Value = value

    def getValue(self):
        return self.Value

    def setValue(self,v): 
        self.Value = 0
        if value == 25 or value == 50:
            self.Value = value
    def getDenomiation(self):
        return self.Denomination

    def setDenomination(self, d):
        self.Denomination = d
        
    def __str__(self):
        return str(self.Value)+" " + self.Denomination

class Item(object):
    def __init__(self,n,c,p,q):
        self.Name = n
        self.Code = c
        self.Price = p
        self.Quantity = q
    def getName(self):
        return self.Name
    def setName(self,n):
        self.Name = n

    def getCode(self):
        return self.Code
    def setCode(self,n):
        self.Code = n
    def getPrice(self):
        return self.Price
    def setPrice(self,n):
        self.Price = n
    def getQuantity(self):
        return self.Quantity
    def setQuantity(self,n):
        self.Quantity = n

    def __str__(self):
        output = "Name: " + self.Name
        output += "\nCode: " + self.Code
        output += "\nPrice: " + str(self.Price)
        output += "\nQuantity: " + str(self.Quantity)
        return output

    
class VendingMachine(object):
    def __init__(self):
        self.allItems = []
        self.amount = 0

    def getItems(self):
        return self.allItems

    def getAmount(self):
        return self.amount
    def setAmount(self,a):
        self.amount = a

    def addItem(self, It):
        for i in self.allItems:
            if i.getCode() == It.getCode():
                i.setQuantity(i.getQuantity() + It.getQuantity())
                return
        self.allItems.append(It)

    def insertCoin(self, cn):
        if cn.getValue() == 25 or  cn.getValue() == 50:
            self.amount += cn.getValue()*1.0/100
    def vendItem(self,code):
        for i in self.allItems:
            if i.getCode() == code:
                if i.getQuantity() > 0:
                    if self.getAmount() >= i.getPrice():
                        self.setAmount(self.getAmount() - i.getPrice())
                        i.setQuantity(i.getQuantity() - 1)
                        print "Name: " + i.Name
                        print "Code: " + str(i.Code)
                        print "Price: " + str(i.Price)
                    else:
                        print "Not Enough Money to Buy " + i.getName() 
                    
                else:
                    print "Quantity Out of Stock"
                return
        print "Item with Code " + str(code)+" does not exist"

    def returnBalance(self):
        print "Amount Returned = "+str(self.getAmount())
        self.setAmount(0)


def printMenu():
    
    print " __________________________"
    print "|Menu                      |"
    print "|--------------------------|"
    print "|  1. Stock an Item        |"
    print "|  2. Display all Items    |"
    print "|  3. Insert 25 cents    |"
    print "|  4. Insert 50 cents    |"
    print "|  5. Buy Item             |"
    print "|  6. Get Change           |"
    print "|  7. Print Current Amount |"
    print "|  8. Exit                 |"
    print "|__________________________|"

def StockItem(Vm):
    name = raw_input("Enter Name of Item> ")
    price = float(raw_input("Enter Price> "))
    code = raw_input("Enter Code> ")
    quant = int(raw_input("Enter Quantity> "))
    itm = Item(name,code,price,quant)
    Vm.addItem(itm)

def DisplayAllItems(Vm):
    itms = Vm.getItems()
    for i in itms:
        print i

def Insert25Cents(Vm):
    C25 = Coin("cents",25)
    Vm.insertCoin(C25)

def Insert50Cents(Vm):
    C50 = Coin("cents",50)
    Vm.insertCoin(C50)

def BuyItem(Vm):
    code = raw_input("Enter Code of Item you want to buy> ")
    Vm.vendItem(code)

def GetChange(Vm):
    Vm.returnBalance()
    
def PrintAmt(Vm):
    print "Current Amount is "+str(Vm.getAmount())

inp = 0
Vmach = VendingMachine()
while inp != 8:
    printMenu()
    inp = int(raw_input("Enter your choice> "))
    if inp == 1:
        StockItem(Vmach)
    elif inp == 2:
        DisplayAllItems(Vmach)
    elif inp == 3:
        Insert25Cents(Vmach)
    elif inp == 4:
        Insert50Cents(Vmach)
    elif inp == 5:
        BuyItem(Vmach)
    elif inp == 6:
        GetChange(Vmach)
    elif inp == 7:
        PrintAmt(Vmach)
    elif inp == 8:
        print "Thank you for your business"

The code is working, as I said before, I need to put in an elegant-simple interface too.

Thanks

What do you want to do in Tkinter other than the menu, and what do you want the entire program to do? A couple of comments:

def __init__(self,denom,value):
        self.Denomination = "CENTS"
        self.Value = 0

        ## if the value is not 25 or 50 then self.Value remains at zero
        ## what if someone uses 2 dimes and a nickel?
        ## How can the value be anything other than 25 or 50, since that is all
        ## that your functions will allow which means you don't have to test it.
        if value == 25 or value == 50:
            self.Value = value

    def setValue(self,v): 
        self.Value = 0

        ## you should be getting an error message as "value" has not 
        ## been declared in this function
        if value == 25 or value == 50:
            ## and shouldn't it be "self.Value += coin" to allow for multiple coins
            self.Value = value

Does this code run as is, or do you want to also debug it?

Instead of a class for each item in the vending machine, with a bunch of functions that do nothing other than return the value of the variable, how about using a dictionary instead, in the VendingMachine class. self.item_dict[name] = [code, price, quantity]. Also, I would put Insert25Cents and Insert50Cents under the BuyItem function since you don't know what some one should insert until they decide to buy and item. Your code is unnecessarily complex, even as practice for using classes. A class is supposed to be self-contained, i.e. has all the functions, variables, etc. necessary which means that VendingMachine should contain everything by itself, so it would have a "insert_coin" function within the class for example, and ask the person the value of the coin, and then let the person select to add another coin if desired, but that is just one person's opinion.

An example of a partial Tkinter interface. You can decide if you want to implement more.

try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

class VendingMachine(object):
    def __init__(self):
        self.item_dict = {}

        self.root = tk.Tk()
        self.root.geometry("100x50+50+200")

        self.create_menu()
        b = tk.Button(self.root, text="Exit Program",
                      command=self.root.quit, bg='red', fg='black')
        b.grid(row=10, column=0)
        self.print_menu()
        self.root.mainloop()

    def add_new_item(self):
        """ retrieves name only as this is just an example
        """
        self.menu_frame.withdraw()   ## shut down option menu for now
        self.add_frame = tk.Toplevel(self.root)
        self.add_frame.geometry("200x150+50+10")

        name_label = tk.Label(self.add_frame, text="Name")
        name_label.grid(row=0, column=0)

        self.entry_1 = tk.StringVar()
        name = tk.Entry(self.add_frame, textvariable=self.entry_1)
        name.grid(row=0, column=1)

        b = tk.Button(self.add_frame, text="Add this", command=self.get_values)
        b.grid(row=1, column=0)
        b = tk.Button(self.add_frame, text="No Add Exit", command=self.exit_item_menu)
        b.grid(row=1, column=1)

        name.focus_set()

    def buy_item(self):
        """ not implemented
        """
        print "buy_item called"

    def create_menu(self):
        """ create the menu in it's own frame, once only.  It can be withdrawn and
            re-displayed
        """
        self.menu_frame = tk.Toplevel(self.root)
        self.menu_frame.geometry("200x100+10+10")

        ## we don't use "b" so all buttons can use "b" to catch the return value
        b = tk.Button(self.menu_frame, text="Add new item",
                      command=self.add_new_item, bg='lightblue', fg='white')
        b.grid(row=0, column=0)
        b = tk.Button(self.menu_frame, text="Buy an item",
                      command=self.buy_item, bg='lightblue', fg='white')
        b.grid(row=1, column=0)
        b = tk.Button(self.menu_frame, text="Update item's quantity",
                      command=self.update_item_quantity, bg='lightblue', fg='white')
        b.grid(row=2, column=0)
        self.menu_frame.grid()
        self.menu_frame.withdraw()  ## withdraw the frame so print_menu can deiconify

    def exit_item_menu(self):
        """ destroy the 'enter new item' frame and display the menu
        """
        self.add_frame.destroy()
        self.print_menu()

    def get_values(self):
        name=self.entry_1.get()
        if name not in self.item_dict:
            ## fill with generic values since we haven't implemented getting values
            self.item_dict[name] = ['code', 'amount', 'quantity']
            print self.item_dict
        else:
            print name, "already on file"
        self.exit_item_menu()

    def print_menu(self):
        """ (re) display the menu
        """
        self.menu_frame.deiconify()

    def update_item_quantity(self):
        """ not implemented
        """
        print "update_item_quantity called"


VM=VendingMachine()

Edited 5 Years Ago by woooee: n/a

What do you want to do in Tkinter other than the menu, and what do you want the entire program to do? A couple of comments:

def __init__(self,denom,value):
        self.Denomination = "CENTS"
        self.Value = 0

        ## if the value is not 25 or 50 then self.Value remains at zero
        ## what if someone uses 2 dimes and a nickel?
        ## How can the value be anything other than 25 or 50, since that is all
        ## that your functions will allow which means you don't have to test it.
        if value == 25 or value == 50:
            self.Value = value

    def setValue(self,v): 
        self.Value = 0

        ## you should be getting an error message as "value" has not 
        ## been declared in this function
        if value == 25 or value == 50:
            ## and shouldn't it be "self.Value += coin" to allow for multiple coins
            self.Value = value

Does this code run as is, or do you want to also debug it?

Instead of a class for each item in the vending machine, with a bunch of functions that do nothing other than return the value of the variable, how about using a dictionary instead, in the VendingMachine class. self.item_dict[name] = [code, price, quantity]. Also, I would put Insert25Cents and Insert50Cents under the BuyItem function since you don't know what some one should insert until they decide to buy and item. Your code is unnecessarily complex, even as practice for using classes. A class is supposed to be self-contained, i.e. has all the functions, variables, etc. necessary which means that VendingMachine should contain everything by itself, so it would have a "insert_coin" function within the class for example, and ask the person the value of the coin, and then let the person select to add another coin if desired, but that is just one person's opinion.

Hello :)
I really appreciate you valuable comment, I can see what do you mean,
the thing is that I was practicing from a book. as the question asked me to use THREE classes and it also asked for only 25 and 50 dirhams.

the code doesn't need debugging. I have checked it and everything is working perfectly. mmm .. Did you try it? did it crash ? please let me know ?

I'm looking for a simple interface. I'm also thinking of removing the adding item choice. and just adding items from a file I'm going to create.

I will post a picture of how I think It should look like.

THANK YOU guys, U are inspirational!

Hello
What im trying to code is something to satisfy this task.

hope i can get a reply from you on inbox ..

thanks

Task:
In this assignment, you will implement a Graphical User Interface for the Vending
Machine you made.
When your program starts up, you will open a file called stockup.txt. This file will
contain list of items that will be stocked in the vending machine. The format of the file
will be as follows:
Name, Code, Price, Quantity
An Example file will look like this:
KitKat, A1, 1.25, 10
Coke, A2, 1.5, 5
Pepsi, B1, 1.75,8
There will be at a maximum of 8 items in the file and the codes will always be A1, A2,
B1, B2, C1, C2, D1, and D2. It is possible to have less than 8 items in the file.
Your GUI should have button to press the item code and to insert 25 and 50 cents coins. There should also be a button to get your change back.
You should also implement the following behavior for the vending machine:
1. The top part of the vending machine should show the current amount that is
currently deposited using a label.
2. If the user presses a button to purchase an item and there is not enough money in
the vending machine, the top label should display a message that prints the price
of the item for 5 seconds.
3. If there is enough money in the vending machine, the label should print – “Item
dispensed” for 5 seconds.
4. If the user presses the Get Change button, the label should show the amount given
back to the user for 5 seconds.
5. The balance shown in the label should be updated every time the user enters
money by clicking on the two insert buttons.A Sample picture of the GUI is shown below. Your implementation does not have
to match the picture in looks but it should have the complete functionality.

The link below is the picture that shows an example of what the vending should look like ..

http://www5.0zz0.com/2011/12/06/08/795626652.jpg

The following website will show you lots of help about different widgets available to you
through the Tkinter library.
http://www.pythonware.com/library/tkinter/introduction/
You may want to use a Label for items that are just information and Buttons for the buttons that will be clicked

This article has been dead for over six months. Start a new discussion instead.