1

I am confused about where to put the mainloop function in python. When I use this code:

from tkinter import *
import sys
window = Tk()
def mainFunct():
    while True:

        label = Label(window,text="Hello World")
        label2 = Label(window, text = "Hello World2")
        menu = input("Please input something")
        if menu == "a":
            label.pack()
        if menu == "b":
            label2.pack()
        if menu == "c":
            sys.exit()

        window.mainloop()
mainFunct()

I want label to be packed when the user inputs a and when the user inputs b i want label2 to be packed. I am not sure when and why to use mainloop. Right now when I run the program, the GUi only pops up after I have inputted something and then I can't even input anything else and I think it has some thing to do with the window.mainloop() function because it just loops over and over again instead of running the while True loop again.

1 Answer 1

1

I was able to understand your question better based off of the comment. Let me know if this is what you're looking for:

import tkinter as tk

class HelloWorld(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="What's your input?", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        answer = self.entry.get()
        if answer == "a":
            print("Hello World")
        elif answer == "b":
            print("Hello World 2")
        elif answer == "c":
            root.destroy()

root = HelloWorld()
root.mainloop()

So when dealing with the input of a user it's better to create a class and from that obtain/compare the information.

Now if the answer is anything other than a, b, or c there will be no response from the program, so adjust accordingly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response!, I have either way I put the mainloop() it will just loop infinitely... so if I have it before the mainFunct then it will just show the screen and if I have it other the mainFunct() then the labels will only pack after I type in "c". E.g. 'code' mainFunct() root.mainloop() 'code' The GUI interface will only pop up after the mainFunction but how do I pack things when I want the mainFunction to loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.