Home > other >  How do I delete text when I press a button? (tkinter)
How do I delete text when I press a button? (tkinter)

Time:12-22

So I am trying to make a script that can by the click of a button choose randomly an even or an odd number and then tell you if it was even or odd. But I can't make it delete the text after I press the button so it just puts the text below. Sry If my message is unclear

from tkinter import *
import random
import time
from tkinter import font

root = Tk()
root.geometry("960x540")

def numberTeller():

    randomNumber = random.randint(1,2)

    if (randomNumber%2) == 0:
        evenOrOdd = Label(root, text="Even")
        evenOrOdd.pack()
    else:
        evenOrOdd = Label(root, text="Odd")
        evenOrOdd.pack()

button = Button(text="Click for random even or odd",font=("robotto",27),command=numberTeller)

button.pack()

root.mainloop()

[enter image description here][1]

[1]: https://i.stack.imgur.com/WELDU.png <-- Image link

CodePudding user response:

You don't need to create a new label, create one label and then just configure it as needed:

from tkinter import Tk, Button, Label
import random


def number_teller():
    random_number = random.randint(1, 2)
    if random_number % 2 == 0:
        even_or_odd.config(text='Even')
    else:
        even_or_odd.config(text='Odd')


root = Tk()
root.geometry("960x540")

button = Button(
    text="Click for random even or odd", font=("robotto", 27),
    command=number_teller)

even_or_odd = Label(root)

button.pack()
even_or_odd.pack()

root.mainloop()

Also:
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.

I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case, class names in CapitalCase. Don't have space around = if it is used as a part of keyword argument (func(arg='value')) but have space around = if it is used for assigning a value (variable = 'some value'). Have space around operators ( -/ etc.: value = x y(except here value = x y)). Have two blank lines around function and class declarations. Object method definitions have one blank line around them.

  • Related