Home > Net >  ImportError with tkinter
ImportError with tkinter

Time:12-03

So I found tutorial about work with GUI in python tkinter
then I try to learn it from w3school, I copied the sample code:

from tkinter import *
from tkinter .ttk import *

root = Tk()
label = Label(root, text="Hello world Tkinket GUI Example ")
label.pack()
root.mainloop()                 

So, I google how to install tkinter on ubuntu. I used:

$ sudo apt-get install python-tk python3-tk tk-dev
$ sudo apt-get install python-tk             
$ pip install tk      

It's seem it was successfully but I was wrong..

I get this errors:
enter image description here

Ubuntu 22.04.1 LTS

CodePudding user response:

I think you can just remove the line: from tkinter .ttk import * I don't think you need that line to run this code.

CodePudding user response:

I believe you only need to use: from tkinter import *

I'd say get rid of the: from tkinter .ttk import *

CodePudding user response:

Generally what you want is

import tkinter as tk  # 'as tk' isn't required, but it's common practice
from tkinter import ttk  # though you aren't using any ttk widgets at the moment...

I know star imports have a certain appeal, but they can lead to namespace pollution which is a huge headache!

For example lets say I've done the following:

from tkinter import *
from tkinter.ttk import *

root = Tk()
label = Label(root, text='Hello!')

is Label a tkinter widget or a ttk widget? I don't know, and the interpreter doesn't either!

Conversely...

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
label = ttk.Label(root)

Here, it's clear that label is a ttk widget. Now everything is namespaced appropriately, and everyone's happy!

  • Related