Python Forum
Use a button in Tkinter to run a Python function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use a button in Tkinter to run a Python function
#1
I use Python functions to create html. I made a module, cunningly called 'makeHTML.py' I import this module in justMakewebpage.py I have refined this over the last 3 years or so, it all works well, and does what I want. I run justMakewebpage.py in a bash terminal.

Now, I would like to try to have a GUI for this. I haven't really used Tkinter before.

I have this button:

bt = Button (window, text="Enter", bg="orange", fg="red", command=clicked)
    bt.grid (column=3, row=3)
this label:

l4 = Label(window,text='Some text', font="Times 15 bold")
    l4.grid (column=4, row=4)
and this function:

def clicked(): 
     l4.configure (text="Button was clicked !!")
So I'm thinking, I can link buttons to my individual create-html-functions.

Most of my create-html-functions require some input from me, like: "Do you want the words in the table sorted alphabetically?"

I'm not asking you to give me the code. If you could just point me at some links where someone has done this.

I can't really create code, but I can usually adapt other people's programmes to suit my purposes.

Thanks in advance for any tips or links.
Reply
#2
Before you get started, You should investigate other GUI packages.

Tkinter is great if you don't plan anything really fancy, but it's handling of geography, frankly sucks.
I did write a tuttial on how to get this right, here: https://python-forum.io/Thread-Tkinter-G...first-time

I'd suggest taking a look at Qt5 (Note that this is a commercial product with a community edition that has been
available for quite some time). It's probably the best package out there. Personally I don't use it, because I've
been burnt in the past by code that dropped their 'free' product.

Kivy is well liked, and I'm told works well for mobile applications.

My choice is wxpython phoenix. It's written for python, and has a very nice widget set. Geometry is a snap, including docking and resizing.

The demo program is outstanding, having three tabs for each widget, one for documentation, another for the actual demo, and a third that contains the source code for the demo. If it doesn't cover 100 % of all widgets it comes mighty close.

I have a demo program that shows a nicely proportioned three window GUI on this forum that you might want to take a look at here.

The documentation is excellent take a look: https://wxpython.org/Phoenix/docs/html/index.html

There is an interactive gallery that will give you an idea of what it has to offer here: https://wxpython.org/Phoenix/docs/html/gallery.html
It can be installed with pip from command line pip install wxpython
Reply
#3
(Jun-26-2020, 10:10 PM)Pedroski55 Wrote: So I'm thinking, I can link buttons to my individual create-html-functions.

Most of my create-html-functions require some input from me, like: "Do you want the words in the table sorted alphabetically?"

If you mean that your functions take input on the command line (i.e. with the input function), then there's your problem: your functions aren't reusable as they are. The correct thing to do then is remove the dependency on reading input from the console. The functions should take the input they need as arguments and then those inputs can come from whatever sources they like: in a command line program, you can obtain the data using input, but in a GUI program, they can be read from text fields or whatever.

Here's an example of a function calculating the area of a circle. It's actually doing two things: as well as performing the calculation, it reads its own input. I suspect you're doing something like that.

import math

def area():
    radius = float(input("Enter the circle radius in metres: "))
    return math.pi * radius ** 2.0

result = area()
print(f"The area is {result} m^2")
As discussed, that's problematic and as I suggested above, here's a better design:

import math

def area(radius):
    return math.pi * radius ** 2.0

radius = float(input("Enter the circle radius in metres: "))
result = area(radius)
print(f"The area is {result} m^2")
Now, the function area only performs the calculation and nothing else. In my example, I take the input from the console and pass it to the function as an argument, but the point is the function is now unaware of where its input comes from. That means you can use it in a console application, a GUI application or whatever else.

Quote:I can't really create code, but I can usually adapt other people's programmes to suit my purposes.

Please take time to learn how to use the tools the language provides you, so that you can write your own programs. What are you going to do when you come across a problem you don't know how to solve and can't easily find code for?
Reply
#4
Thanks for the tips and advice and links! Great!

@Larz60+: No, I don't plan anything fancy. I will be happy if it works at all!

@ndc85430: my little programs do require some input from me, and I make them display some output, just so I know it's working.

For example, textboxes: This takes a text file and inserts text input fields, making a gapped text. The input fields all have a name like G1 or G2 etc. the value of which is given to PHP later.

So I need to tell my programme which text and the start number for GX. Then it presents me with the text, sentence by sentence. I write or copy and paste a word or phrase. The programme then puts an input field where the word or phrase is.

The overall effect is, a gapped text on my webpage and a recording. The students listen to the recording and fill in the gaps.

Yesterday, I found the code below. It has and input field and displays output. I will try to adapt it for my textboxes function.

#! /usr/bin/python3

import tkinter
from tkinter import *
from tkinter import messagebox
from random import randint

def myWindow1():
    window = tkinter.Tk()
    window.title("Calculate the square root")
    window.config(bg='light blue')
    window.geometry('640x480')

    canvas1 = tkinter.Canvas(window, bg='white', width = 400, height = 300,  relief = 'raised')
    canvas1.pack()

    label1 = tkinter.Label(window, text='Calculate the Square Root')
    label1.config(font=('helvetica', 14))
    canvas1.create_window(200, 25, window=label1)

    label2 = tkinter.Label(window, text='Type your Number:')
    label2.config(font=('helvetica', 10))
    canvas1.create_window(200, 100, window=label2)

    entry1 = tkinter.Entry (window) 
    canvas1.create_window(200, 140, window=entry1)

    def getSquareRoot ():
        
        x1 = entry1.get()
        
        label3 = tkinter.Label(window, text= 'The Square Root of ' + x1 + ' is:',font=('helvetica', 10))
        canvas1.create_window(200, 210, window=label3)
        
        label4 = tkinter.Label(window, text= float(x1)**0.5,font=('helvetica', 10, 'bold'))
        canvas1.create_window(200, 230, window=label4)
        
    button1 = tkinter.Button(text='Get the Square Root', command=getSquareRoot, bg='brown', fg='white', font=('helvetica', 9, 'bold'))
    canvas1.create_window(200, 180, window=button1)

    window.mainloop()

myWindow1()
PS:I have no idea how this:

float(x1)**0.5

gets the square root, but it works! Only if you have time, perhaps you could explain it to me
Reply
#5
Finding the nth root of a value x is the same as raising x to the power 1/n.

Let r be the square root of x. Then, we have

r^2 = x

We want to express r in terms of x^m. Our equation becomes

(x^m)^2 = x

Knowing that we can multiply the powers gives

x^2m = x

Finally, comparing powers gives

2m = 1 => m = 1/2

So, in general, if r is the nth root of x, so that

r^n = x,

we find that m = 1/n by going through the same process.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to open a popup window in tkinter with entry,label and button lunacy90 1 902 Sep-01-2023, 12:07 AM
Last Post: lunacy90
  Tkinter button images not showing up lunacy90 7 1,617 Aug-31-2023, 06:39 PM
Last Post: deanhystad
Bug tkinter.TclError: bad window path name "!button" V1ber 2 806 Aug-14-2023, 02:46 PM
Last Post: V1ber
  Closing Threads and the chrome window it spawned from Tkinter close button law 0 1,717 Jan-08-2022, 12:13 PM
Last Post: law
  tkinter auto press button kucingkembar 2 3,196 Dec-24-2021, 01:23 PM
Last Post: kucingkembar
  Partial using Tkinter function chesschaser 10 6,835 Jul-03-2020, 03:57 PM
Last Post: chesschaser
  Problem using a button with tkinter SmukasPlays 6 3,317 Jul-02-2020, 08:06 PM
Last Post: SmukasPlays
  Function assigned at a button in tkinter riccardoob 9 4,198 Oct-06-2019, 11:14 AM
Last Post: riccardoob
  tkinter button executes button before being clicked SheeppOSU 1 3,800 Apr-01-2019, 10:51 PM
Last Post: Yoriz
  Function for clicking a button within a browser NikonNorm 6 4,491 Jun-06-2018, 04:08 PM
Last Post: Grok_It

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020