Home > Software design >  Python Tkinter dialing functionality
Python Tkinter dialing functionality

Time:01-29

I am creating a GUI application using Tkinter that has a number pad and output of dialed numbers after pushing respective buttons. I've searched a little on Tkinter labels and appending them but I can't seem to find anything that works for what I need. I made a function called AppendDialEntry() and assigned that function to each button with the symbol as a passed parameter to append what is already in the label.

Here is a sample of the Append function:

def AppenddialEntry(string):
    
    dialInput = dialEntry.cget("text")   string
    dialEntry.config(text=dialInput) 

dialEntry = tk.Label(root, text="")
dialEntry.grid(row=0, column=4)

And here is one of the buttons:

number_3 = tk.Button(root, text="3", command=AppendDialEntry("3")) 

enter image description here

I am also attaching the GUI to show what I am getting.

CodePudding user response:

Rather than updating the text of the dialEntry widget directly, you can make use of the textvariable attribute so that tkinter takes care of updating the label text whenever that value changes.

Also, rather than hard-coding the button value in a lambda, you could consider binding each button to a click event so that you can just get the button text from the event. This would make it easier to add more buttons and functionality in the future (check out the delete button in the example below).

Here's a full example of how this could be done.

from tkinter import *
from tkinter import ttk

def AppendDialEntry(event):
    buttonText = event.widget.cget('text')
    dialInput.set(dialInput.get()   buttonText)

def backspace():
    dialInput.set(dialInput.get()[:-1])

root = Tk()
root.title("Calc Demo")

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

btnVals = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#']
rowNum = 1
colNum = 1
for val in btnVals:
    btn = ttk.Button(mainframe, text=val)
    btn.grid(column=colNum, row=rowNum)

    # Binding to a click event rather than using command
    btn.bind('<ButtonPress-1>', AppendDialEntry)

    # 3 buttons to a row
    if colNum % 3 == 0:
        rowNum  = 1
        colNum = 1
    else:
        colNum  = 1

backspaceBtn = ttk.Button(mainframe, text="delete", command=backspace)
backspaceBtn.grid(column=1, row=(rowNum   1))

# Setting the label text via the textvariable attribute
dialInput = StringVar()
dialEntry = ttk.Label(mainframe, textvariable=dialInput)
dialEntry.grid(column=1, row=0, sticky=W)

root.mainloop()

CodePudding user response:

Why don't you try putting the command in the button in a lambda function? Like this:

btn3 = tk.Button(root, text = '3', command = lambda : AppendDialEntry('3'))
  • Related