logo
down
shadow

tkinter: assigning multiple functions to one button


tkinter: assigning multiple functions to one button

Content Index :

tkinter: assigning multiple functions to one button
Tag : python , By : ack
Date : November 26 2020, 03:01 PM

it fixes the issue I am trying to construct a Roman numeral converter using Tkinter. I need to use one button which will convert decimals to Roman numerals if numbers are entered, and Roman numerals to decimals if numerals are entered. How do I assign the two functions to one button, and call whichever function corresponds to what is entered? , Add a function to see if the input is a number.
def check_input():
    s = ent.get()
    if (isinstance(s, int)):
        roman_number(s)
    else:
        decimal_number(s)
Convertb = Button(root, text='Convert', command = check_input)

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Problems assigning a value from a randomly populated array to a tkinter button


Tag : python , By : user185144
Date : March 29 2020, 07:55 AM
Does that help This may be what you're wanting to do.
Borrowing info from this answer, I put a callback in the Button command to pass the row and column numbers.
# previous code

amount_to_add='B'  
my_array = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],    
[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]]  

# ... all code up to here unchanged ...

for _ in range(4):
    my_array[random.randrange(len(my_array))][random.randrange(len(my_array))] = amount_to_add   

Treasure='T'
for _ in range(4):
    my_array[random.randrange(len(my_array))][random.randrange(len(my_array))] = Treasure  

# print my_array # uncomment to check array values before shuffle
random.shuffle(my_array)
# print my_array # and after shuffle to confirm button is getting the correct values

def changelabel(j,k):
    tkinter.messagebox.showinfo('Button %d,%d' % (j,k), 'Button %d,%d contains a %s' % (j,k, my_array[j][k]))
        print('hello this button works')
        # return # not needed  

i = 0  
bttn = []

for j in range(0,8):   
    for k in range(8):
        bttn.append(Button(TreasureMap, text = ' ', command= lambda row = j, column = k: changelabel(row, column)))
        bttn[i].grid(row = j, column = k)           
        i += 1

tkinter: use single button with multiple frames and functions


Tag : python , By : 3NZ0
Date : March 29 2020, 07:55 AM
hop of those help? Iterating over frames[1:4] won't work very well here, as it leaves you with no easy way to get the next/previous frame. Try iterating over indices instead:
for i in range(1,4):
    nb = Button(frames[i], text="Next", command=frames[i+1].tkraise)
    nb.pack(side=RIGHT)
    pb = Button(frames[i], text="Previous", command=frames[i-1].tkraise)
    pb.pack(side=LEFT)
for i in range(len(frames)):
    if i != len(frames) - 1:
        nb = Button(frames[i], text="Next", command=frames[i+1].tkraise)
        nb.pack(side=RIGHT)
    if i != 0:
        pb = Button(frames[i], text="Previous", command=frames[i-1].tkraise)
        pb.pack(side=LEFT)

Assigning functions to buttons created in a for loop in Tkinter


Tag : python , By : Priyatna Harun
Date : March 29 2020, 07:55 AM
hop of those help? I have a for loop which creates an amount of buttons (in tkinter) based on the length of my list, compkeys. When I make each button, it is given a previously made function which takes one input. I am trying to make the input of the function specific to the iteration of the for loop. For example, the first button that is created in the loop should have the first item in the list comp keys as input in its function. , You must pass the parameter through the lambda function:
for x in range(len(compKeys)):
    compButton = Button(root, text=compKeys[x], command=lambda z=compKeys[x]: compBuDef(z))
    compButton.place(x=x*100+200, y=300)
for idx, ckey in enumerate(compKeys):
    compButton = Button(root, text=ckey, command=lambda z=ckey: compBuDef(z))
    compButton.place(x=idx*100+200, y=300)

Tkinter radio button assigning last variable when run?


Tag : python , By : Tamizhvendan
Date : November 01 2020, 04:01 AM
this will help I have three files and I am trying to change the value of a variable through radio buttons: , Consider this line of code:
epochRadioButton20 = Radiobutton(..., command=changeEpoch(20))
result = changeEpoch(20)
epochRadioButton20 = Radiobutton(..., command=result)
def changeEpoch():
    epochValue = var1.get()
    config.epoch=epochValue
...
epochRadioButton20 = Radiobutton(..., command=lambda: changeEpoch)
epochRadioButton20 = Radiobutton(..., command=lambda: changeEpoch(20))

How can I connect multiple text field inputs along with their functions to one button in tkinter python?


Tag : python , By : user119413
Date : March 29 2020, 07:55 AM
Hope this helps I have this issue where I need to display other function's values using the only button which is Calculate in this case. The first function is displayed but the other function not while using its text input field.
import tkinter as tk
from statistics import median, mode, stdev

class Calculator(tk.Frame):
    """Calculate mean median mode and standard deviation"""
    def __init__(self, parent, *args, **kwargs):
        #setup tkinter frame
        tk.Frame.__init__(self, parent, *args, **kwargs)
        parent = parent

        self.makeWidgets()

    def makeWidgets(self):
        """make and pack various widgets"""
        self.meanLabel = tk.Label(self, text="")
        self.medianLabel = tk.Label(self, text="")
        self.modeLabel = tk.Label(self, text="")
        self.sdLabel = tk.Label(self, text="")
        self.entry = tk.Entry(self)
        self.calcuateButton = tk.Button(self, text="Calculate!", command = self.calculate)
        self.meanLabel.pack()
        self.medianLabel.pack()
        self.modeLabel.pack()
        self.sdLabel.pack()
        self.entry.pack()
        self.calcuateButton.pack()

    def calculate(self):
        self.listOfNumbers = self.entry.get()
        #get what is inputed into the entry widget
        self.listOfNumbers = self.listOfNumbers.split(' ')
        #split the input string by spaces
        for ind, i in enumerate(self.listOfNumbers):
            #convert each item in the list of strings of numbers to ints
            self.listOfNumbers[ind] = int(i)
        #calculate!
        self.calcMean()
        self.calcMedian()
        self.calcMode()
        self.calcSd()

    def calcMean(self):
        """calculate the mean"""
        mean = sum(self.listOfNumbers)/len(self.listOfNumbers)
        self.meanLabel.config(text='mean = ' + str(mean))
        return mean

    def calcMedian(self):
        """calculate the median"""
        med = median(self.listOfNumbers)
        self.medianLabel.config(text='median = ' + str(med))
        return med

    def calcMode(self):
        """calculate the mode"""

        Mode = max(set(self.listOfNumbers), key=self.listOfNumbers.count)
        self.modeLabel.config(text='mode = ' + str(Mode))
        return Mode

    def calcSd(self):
        """calculate the standard deviation"""
        sd = stdev(self.listOfNumbers)
        self.sdLabel.config(text='Standard deviation = ' + str(sd))
        return sd

if __name__ == '__main__':
    root = tk.Tk()
    root.title('calculate mean, median, mode and standard deviation')
    root.geometry('400x200')
    Calculator(root).pack(side="top", fill="both", expand=True)
    root.mainloop() 
Related Posts Related QUESTIONS :
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • How to speed up calculating variance among sparse matrix
  • cupy code is not fast enough compared with numpy
  • How to count frequency of select values in Python pandas dataframe
  • Scrape Span Text from Google
  • Python watchdog, watch a directory and rename file on event.modification
  • Filtering rows in DataFrame with dependent conditions
  • How to check if a character is a not a part of number or URL in string?
  • Compare corresponding elements of a list
  • Python misinterprets 3 character string as UTF-8 continuation byte
  • Merge two columns in Pandas
  • Side Effect error in Python in an online compiler
  • How to convert a navigation list with depth levels to a parent-child flat list?
  • Retrieving values from a paired key dictionary in Python
  • How to test the current text of a Tkinter text box widget before inserting new text after user clicks on a button?
  • computing the Cumulative Sum, where Sum can be reset by a condition
  • Where do you specify your API key when making a request with the Google API python library?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com