NameError: name 'tk' is not defined repl.it - python

hey beginner programmer here, making a to do list for a high school assignment and cant figure out this error. its also my first time using python as I usually use java and JavaScript for projects. Im trying to add a dark and light mode to my program. Am I doing this correctly? btw, i'm using the online ide repl.it
here's my code for reference
import tkinter
import tkinter.messagebox
from ttkthemes import ThemedStyle
import tkinter.ttk as ttk
import pickle
root = tkinter.Tk()
root.title("To-Do List")
def add_task():
task = entry_task.get()
if task != "":
listbox_tasks.insert(tkinter.END, task)
entry_task.delete(0, tkinter.END)
else:
tkinter.messagebox.showwarning(title="Warning", message="Please enter a task")
def delete_task():
try:
task_index = listbox_tasks.curselection()[0]
listbox_tasks.delete(task_index)
except:
tkinter.messagebox.showwarning(title="Warning", message="Please select a task first")
def load_tasks():
try:
tasks = pickle.load(open("tasks.dat", "rb"))
listbox_tasks.delete(0, tkinter.END)
for task in tasks:
listbox_tasks.insert(tkinter.END, task)
except:
tkinter.messagebox.showwarning(title="Warning", message="Cant find saved task file")
def save_tasks():
tasks = listbox_tasks.get(0, listbox_tasks.size())
pickle.dump(tasks, open("tasks.dat", "wb"))
# Dark and light modes
app = tk.Tk()
app.geometry("200x400")
app.title("Changing Themes")
# Setting Theme
style = ThemedStyle(app)
style.set_theme("scidgrey")
# Button Widgets
Def_Btn = tk.Button(app,text='Default Button')
Def_Btn.pack()
Themed_Btn = ttk.Button(app,text='Themed button')
Themed_Btn.pack()
# Scrollbar Widgets
Def_Scrollbar = tk.Scrollbar(app)
Def_Scrollbar.pack(side='right',fill='y')
Themed_Scrollbar = ttk.Scrollbar(app,orient='horizontal')
Themed_Scrollbar.pack(side='top',fill='x')
# Entry Widgets
Def_Entry = tk.Entry(app)
Def_Entry.pack()
Themed_Entry = ttk.Entry(app)
Themed_Entry.pack()
# Create GUI
frame_tasks = tkinter.Frame(root)
frame_tasks.pack()
listbox_tasks = tkinter.Listbox(frame_tasks, height=10, width=50)
listbox_tasks.pack(side=tkinter.LEFT)
scrollbar_tasks = tkinter.Scrollbar(frame_tasks)
scrollbar_tasks.pack(side=tkinter.RIGHT, fill=tkinter.Y)
listbox_tasks.config(yscrollcommand=scrollbar_tasks.set)
scrollbar_tasks.config(command=listbox_tasks.yview)
entry_task = tkinter.Entry(root, width=50)
entry_task.pack()
button_add_task = tkinter.Button(root, text="Add a task", width=48, command=add_task)
button_add_task.pack()
button_delete_task = tkinter.Button(root, text="Delete a task", width=48, command=delete_task)
button_delete_task.pack()
button_load_tasks = tkinter.Button(root, text="Load a task list", width=48, command=load_tasks)
button_load_tasks.pack()
button_save_tasks = tkinter.Button(root, text="Save your task list", width=48, command=save_tasks)
button_save_tasks.pack()
root = tkinter()
root.mainloop()

repl.it has nothing to do with the issue. You have lines referencing "tk", like app = tk.Tk(), but you never defined anything called tk. It looks like some of your code expects you to have imported Tkinter via import tkinter as tk, in which case tk would be valid. But you also have code expecting it to be called tkinter, like root = tkinter.Tk(). It seems like your code was inspired from multiple sources, some of which had Tkinter imported as tk, and some where it was imported as tkinter. All you have to do is replace all tks with tkinter. For example, this line:
Def_Btn = tk.Button(app,text='Default Button')
would become:
Def_Btn = tkinter.Button(app,text='Default Button')

The problem is probably coming from your import
I observed that you did not import Tkinter as tk but you keep on using the tk. try importing it

Since you have:
import tkinter
Python looks for tkinter not tk since you have not told python that you want to use the module with the alias 'tk'
Your solution is:
import tkinter as tk
You probably forgot that you were using tkinter instead of tk.

The problem is from your import statement, you imported tkinter as ttk but you kept on using tk

Related

Change right click event of tkinter command

I want to detect the right click event on tkinter Menu command.
Consider code below.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
menu_button = ttk.Menubutton(root, text="MENU")
menu_button.grid()
m = tk.Menu(menu_button, tearoff=False, activeborderwidth=0)
menu_button["menu"] = m # To avoid garbage collection
m.add_command(label="an option", command=lambda: print("option1"))
m.add_command(label="another option", command=lambda: print("option2"))
root.mainloop()
When I click an option or another option, the commands are called as expected. But want I want to do is catch right click event. Can anyone knows that how can I detect it?
use button.bind("<Button-3>", event). Consider this code:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
button = tk.Button(root, text='right click this')
button.pack()
button.bind("<Button-3>", lambda e: print('You right clicked'))
root.mainloop()

Starting another script from button press on tkinter

so I am trying to create a button on tkinter that runs another script. I'm not sure whether this is the most optimal way rather than just adding whatever I have onto the script I want to run but I want to see if this is possible for future references. This is what I have on my script so far. Any ideas on how to approach this?
import tkinter as tk
from tkinter import *
from tkinter import simpledialog
import uploadtest as ut
class Initial(simpledialog.Dialog):
def body(self, master):
#input fields for username and passwords
Label(master, text="Scripts").grid(row=1, column=1),
#Buttons
self.utz = ut
self.b1 = Button(master, text = "Script1", bg="grey", command=self.utz)
self.b1.grid(row=7, column=1, ipadx=75)
root = tk.Tk()
root.withdraw()
d = Initial(root)
Any help would be greatly appreciated. I know I can just add this class to the other script and use the button command and it would be easier, but I was just curious if this method was possible since I am going to be adding multiple scripts to this and I would like to have my scripts separated. It seems like when I try to import uploadtest.py on this script, it just runs that script instead of this one.
if you want to use it again for future references you can modify your uploadtest.py to be a function
def ut():
print("your")
print("script")
print("here")
then to use it in the script do from uploadtest import * and call it like a normal function that's in your script
import tkinter as tk
from tkinter import *
from tkinter import simpledialog
from uploadtest import *
class Initial(simpledialog.Dialog):
def body(self, master):
#input fields for username and passwords
Label(master, text="Scripts").grid(row=1, column=1),
#Buttons
self.utz = ut
self.b1 = Button(master, text = "Script1", bg="grey", command=self.utz)
self.b1.grid(row=7, column=1, ipadx=75)
root = tk.Tk()
root.withdraw()
d = Initial(root)
please comment if this is not what your looking for

How to import all under a function

I have a login screen that once logged in will take me to a page that has two buttons. Canteen page button, and admin page button.
my first problem is that once I open my canteen page by pressing the button everything that's inside this page doesn't seem to be working. I assume I have to 'import * from Canteen' although I cant import all under a module.
my second problem is the same as the first just with my Admin screen.
def adminpage():
import Admin
def canteenpage():
import Canteen
find_user = ('SELECT * FROM user WHERE username = ? and password = ?')
c.execute(find_user,[(self.username.get()),(self.password.get())])
result = c.fetchall()
if result:
root=Tk()
root.geometry("400x400")
root.title("Select Page")
Label(text = "welcome to the dashboard").pack()
Button(root, text = "Canteen Page",command=canteenpage).pack()
Button(root, text = "Admin Page",command=adminpage).pack()
As my comment stated if you would like to import the contents of a module you do from Canteen import *
However I don't think importing a module would encapsulate the behaviour you would like to achieve. Your code seems to suggest that you would like to serve the result of a database query in a new window.
For that kind of behaviour I suggest checking out either message widget or messagebox widget of tkinter and adapt your code to use either one of them.
You should put all the code in the other module(In your case "Admin" and "Canteen") in a class. That would work for you.
Like I have done in this example:
Module_1:
import tkinter as tk
def test_func():
from Module_2 import TestClass
root = tk.Tk()
b = tk.Button(root, text="Click", command=lambda: test_func())
b.pack()
root.mainloop()
Module_2:
class TestClass:
import tkinter as tk
root = tk.Toplevel()
lbl = tk.Label(root, text="Test Label")
lbl.pack()
This will work for you

Tkinter progress bar during telnet session

I want to push some configlines through a telnetsession from a tkinter gui.
Simplified; in my GUI I have a button. After pressing this button the telnet session starts (it fetches the config lines from an external fileshare).
But at this moment it is not very user friendly, there is now way to tell whether it is still busy or not. I want to fix this by a progress bar popup.
I've got my main script with all the fetching of the configuration files, adapting and sending it to a switch.
I got a "standalone" script with the popup progress bar.
Now I want to combine those two, but it won't work. I've read about multi-threading, but since I'm new to coding I need some help to understand how this works, if it is needed in my case
The mainscript:
#window stuff
window = Tk()
window.geometry('700x500')
window.title("Switchconfig generator")
window.lift()
def btntelnetclicked():
try:
telnet()
except:
messagebox.showinfo("Status", "Something went wrong, config was not pushed.")
#buttons
btntelnet= Button(window, text="Push config", command=btntelnetclicked)
btntelnet.grid(column=2, row=4, padx=10, pady=10)
This is offcourse just a little piece of code
The progressbar
import threading
try: import tkinter
except ImportError:
import Tkinter as tkinter
import ttk
else: from tkinter import ttk
class GUI_Core(object):
def __init__(self):
self.root = tkinter.Tk()
self.progbar = ttk.Progressbar(self.root)
self.progbar.config(maximum=4, mode='indeterminate')
self.progbar.pack()
self.b_start = ttk.Button(self.root, text='Start')
self.b_start['command'] = self.start_thread
self.b_start.pack()
def start_thread(self):
self.b_start['state'] = 'disable'
self.progbar.start()
self.secondary_thread = threading.Thread(target=arbitrary)
self.secondary_thread.start()
self.root.after(50, self.check_thread)
def check_thread(self):
if self.secondary_thread.is_alive():
self.root.after(50, self.check_thread)
else:
self.progbar.stop()
self.b_start['state'] = 'normal'
def arbitrary():
btntelnetclicked()
gui = GUI_Core()
gui.root.mainloop()

Trouble With Tkinter in Python [duplicate]

I'm trying to make a simple outline for a gui, and I'm getting the warning
"variable" May be undefined or defined from star imports: tkinter for all of my variables.
Here is my code:
from tkinter import *
class myApp :
def __init__(self, gui,) :
self.root = gui
self.bframe = Frame(self.root) # Create a container Frame at bottom
self.bframe.pack(side=BOTTOM)
self.xlabel = Label(self.root, text="Item ID") # Create the Label
self.xlabel.pack(side=LEFT)
self.xentry = Entry(self.root, bd=5) # Create the Entry box
self.xentry.pack(side=LEFT)
self.xentry.bind('<Return>', self.showStockItem)
self.xentry.focus_set() # Set focus in the Entry box
self.xopen = Button(self.root, text="Show", command=self.showStockItem) # Create the open Button
self.xopen.pack(side=LEFT)
self.xquit = Button(self.bframe, text="Quit", command=self.quitit) # Create the quit Button
self.xquit.pack(side=BOTTOM)
return
gui = Tk()
gui.title("Travel")
app = myApp(gui)
gui.mainloop()
from tkinter import *
In this line, you import everything from tkinter. This is not recommended, so linter will warn you. But if you really want to do this, it's OK, just ignore it.
To be better, you should explicitly import what you need. For example:
from tkinter import Tk, Label, Frame, Entry, Button
Consider using:
import tkinter as tk
and then, prefix all your calls like:
root = tk.Tk()
or,
variableName.pack(side = tk.LEFT)
and so on...

Categories

Resources