Search code examples
pythonvisual-studio-codetkinter

How do I import TKinter to python if I use VS code?


I'm trying to import Tkinter into Python using VS code

I've already used the from Tkinter import * command but it seems to do nothing once I run it

Am I running it in the wrong place? Have I misspelt something? Are there more commands I need to run?

(I'm using Python 3.12.0 on Windows 10)


Solution

  • A few things:

    1. The module name is tkinter, not Tkinter (these names are case-sensitive)
    2. Just running the code from tkinter import * won't cause anything noticeable to happen. You've imported tkinter, but you haven't done anything else with it.

    Here's a very minimal example tkinter app that will pop up a window with some text on it

    # this is the typical way to import tkinter; star imports should be avoided
    import tkinter as tk  
    
    # "instantiate" the Tk class - this is your main app instance
    root = tk.Tk()  # root is just a name, but it's the one most people use
    # 'tk' above refers to the alias we gave 'tkinter' in the import statement
    # Tk() is the base application class
    
    # the 'geometry' property lets us set the size of our 'root' window
    root.geometry('200x100')
    
    # now let's create a 'Label' widget that's a child of our 'root' window
    label = tk.Label(root, text='Hello!')  # again 'label' is just a name
    # 'pack()' is a 'geometry manager'; it tells our app to put this widget on the window
    label.pack()
    
    # lastly, to start our app we have to run the 'mainloop()'
    root.mainloop()
    

    I recommend following some tkinter tutorials to get started and familiarize yourself with the basic widget classes and the typical structure of a tkinter app.