Chinmay Desai
Chinmay Desai

Reputation: 3

How can I make a Print and Clear button GUI which prints and clears a Label in Python?

I am a beginner programmer and I am trying to solve a very small problem. I want to make a GUI which has 2 buttons namely, Print and Clear. I tried my best but cant solve it yet. Wanted Help.... Here is my code( ignore neatness ):

from tkinter import *

main = Tk()
main.geometry("200x200")
global buttonstate



def change():

    buttonstate = True
    return buttonstate


button1 = Button(main, text="Button", command=change)

if buttonstate==True:
   global label
   label = Label(main, text= "this works")

elif buttonstate==False:
    pass

button2 = Button(main, text="clear", command=lambda: label.pack_forget())

button1.pack()
button2.pack()
label.pack()

main.mainloop()

I am unable to do all the thing in a loop and also to print the statement when the button is clicked... Thanks.

Upvotes: 0

Views: 300

Answers (1)

Somraj Chowdhury
Somraj Chowdhury

Reputation: 1043

Here is the GUI with two buttons and a label,

from tkinter import *

main = Tk()

# label where you will print text
text_label = Label(main, width=20)
text_label.grid(row=0, columnspan=2, padx=8, pady=4)

# function to print text in label
def print_text():
    # the message you want to display
    your_text = "Some message.."
    # update the text of your label with your message
    text_label.config(text=your_text)

# function to clear text in label
def clear_text():
    # clear the label text by passing an empty string
    text_label.config(text='')

# print button
# command option is the function that you want to call when the button is pressed
print_btn = Button(main, text='Print', command=print_text, width=8)
print_btn.grid(row=1, column=0, padx=8, pady=4)

# clear button
clear_btn = Button(main, text='Clear', command=clear_text, width=8)
clear_btn.grid(row=1, column=1, padx=8, pady=4)

main.mainloop()

Output GUI

Click Print button to print message

print button

Click Clear button to clear message

clear button

I have commented each segment of the code. Hope you understand

Upvotes: 1

Related Questions