I was wondering how I could hide my canvas from the user and then make it reappear when I want it to. I tried using canvas.config(state = "disabled") but it doesn't hide it. When I try canvas.config(state = "hidden") it will say I have to use normal or disabled. Here is the code:
from tkinter import *
from tkinter import ttk
root = Tk()
def redCallback():
labelRed = ttk.Label(frameTwo, text = "Red", background = "red")
labelRed.grid(row = 1, column = 0, pady = 5, ipadx = 35, ipady = 5)
def orangeCallback():
labelOrange = ttk.Label(frameTwo, text = "Orange", background = "orange")
labelOrange.grid(row = 1, column = 1, pady = 5, ipadx = 25, ipady = 5)
def yellowCallback():
labelYellow = ttk.Label(frameTwo, text = "Yellow", background = "yellow")
labelYellow.grid(row = 1, column = 2, pady = 5, ipadx = 26, ipady = 5)
def greenCallback():
labelGreen = ttk.Label(frameTwo, text = "Green", background = "green")
labelGreen.grid(row = 1, column = 3, pady = 5, ipadx = 30, ipady = 5)
def blueCallback():
labelBlue = ttk.Label(frameTwo, text = "Blue", background = "blue")
labelBlue.grid(row = 1, column = 4, pady = 5, ipadx = 33, ipady = 5)
def return_press(event):
labelCanvas = ttk.Label(frameThree, text = "Now draw on the canvas!")
labelCanvas.pack()
def mouse_press(event):
global prev
print('type: {}'.format(event.type))
print('widget: {}'.format(event.widget))
print('num: {}'.format(event.num))
print('x: {}'.format(event.x))
print('y: {}'.format(event.y))
print('x_root: {}'.format(event.x_root))
print('y_root: {}\n'.format(event.y_root))
prev = event
def draw(event):
global prev
canvas.create_line(prev.x, prev.y, event.x, event.y, width = 5)
prev = event
frameOne = ttk.Frame(root)
frameOne.pack()
frameTwo = ttk.Frame(root)
frameTwo.pack()
frameThree = ttk.Frame(root)
frameThree.pack()
labelPallet = ttk.Label(frameOne, text = "Click the buttons below, and then tap ENTER")
labelPallet.pack()
buttonRed = ttk.Button(frameTwo, text = "Red", command = redCallback)
buttonRed.grid(row = 0, column = 0, ipadx = 10, ipady = 5)
buttonOrange = ttk.Button(frameTwo, text = "Orange", command = orangeCallback)
buttonOrange.grid(row = 0, column = 1, ipadx = 10, ipady = 5)
buttonYellow = ttk.Button(frameTwo, text = "Yellow", command = yellowCallback)
buttonYellow.grid(row = 0, column = 2, ipadx = 10, ipady = 5)
buttonGreen = ttk.Button(frameTwo, text = "Green", command = greenCallback)
buttonGreen.grid(row = 0, column = 3, ipadx = 10, ipady = 5)
buttonBlue = ttk.Button(frameTwo, text = "Blue", command = blueCallback)
buttonBlue.grid(row = 0, column = 4, ipadx = 10, ipady = 5)
canvas = Canvas(root, width = 640, height = 480, background = "white")
canvas.pack()
root.bind("<Return>", return_press)
canvas.bind('<ButtonPress>', mouse_press)
canvas.bind("<B1-Motion>", draw)
Currently the program just has buttons, that when clicked, will create labels in that colour. I want the canvas to be hidden until the labelCanvas is printed.
Related
I started working with tkinter recently and I have the following problem, I need to make the check box bigger but that is only possible with adding an image. The problem is that whenever I add an image to a button it becomes unclickable and the image is not displayed, here is my source code (part of a bigger project). My goal is to display some information and let the user decide which option he gets to keep using the check button. Any help is appreciated.
import tkinter as tk
import tkcalendar as tkc
LARGE_FONT = ("HELVETICA", 32, 'bold')
NORMAL_FONT = ("calibri", 18)
class ConstituireDosar(tk.Toplevel):
def __init__(self, controller):
tk.Toplevel.__init__(self)
self.update_idletasks()
# self.dosar = dosar
self.controller = controller
self.minsize(651, 569)
# self.maxsize(651, 569)
frame_titlu = tk.Frame(self)
frame_titlu.grid(row = 0, column = 0)
frame_continut = tk.Frame(self)
frame_continut.grid(row = 1, column = 0, sticky = "w")
frame_acte = tk.Frame(self)
frame_acte.grid(row = 2, column = 0)
titlu = tk.Label(frame_titlu, font = LARGE_FONT, text = "Constituire Dosar")
titlu.grid(row = 0 , column = 0, padx = 10, pady = 15)
data_emiterii = tk.Label(frame_continut, font = NORMAL_FONT,text = "Data emiterii documentului:")
data_emiterii.grid(row = 1, column = 0, padx = 10, pady = 5, sticky = "w")
self.cal = tkc.DateEntry(frame_continut, date_pattern = "DD/MM/YYYY", width = 20)
self.cal.grid(row = 2, column = 0, padx = 10, pady = 5, sticky = "w")
debitori_label = tk.Label(frame_continut, font = NORMAL_FONT, text = "Selecteaza debitorii.")
debitori_label.grid(row = 3, column = 0, padx = 10, pady = 5, sticky = "w")
debitori = []
tip_debitori = []
for i in range(2):
debitori.append("Person %s " % str(i))
tip_debitori.append("Person %s type" % str(i))
for i in range(len(debitori)):
print(debitori[i])
row_i = 4
self.vars_debitori = []
on_image = tk.PhotoImage(width=48, height=24)
off_image = tk.PhotoImage(width=48, height=24)
on_image.put(("green",), to=(0, 0, 23,23))
off_image.put(("red",), to=(24, 0, 47, 23))
for i in range(len(debitori)):
var = tk.IntVar(frame_continut, value = 0)
interior = debitori[i] + " - " + tip_debitori[i]
# Checkbutton(ws, image=switch_off, selectimage=switch_on, onvalue=1, offvalue=0, variable=cb1, indicatoron=False, command=switchState)
checkbuton = tk.Checkbutton (frame_continut, bd = 5, image = off_image, selectimage = on_image, indicatoron = False, onvalue = 1, offvalue = 0, variable = var, state = tk.ACTIVE, command = lambda: self.toggle(var))
checkbuton.grid(row = row_i, column = 0, padx = 20, pady = 5, sticky = "nw")
checkbuton.image = off_image
# checkbuton.select()
self.vars_debitori.append(var)
row_i += 1
self.vars_acte = []
acte = ["Acte de Procedura", "Incheiere de Admitere", "Cerere de Incuviintare", "Instiintare Creditor"]
for i in range(4):
v = tk.IntVar()
check = tk.Checkbutton(frame_acte, font = NORMAL_FONT, text = acte[i], variable = v)
check.grid(row = row_i, column = 0, padx = 10, pady = 5)
check.select()
self.vars_acte.append(v)
row_i += 1
emite_acte = tk.Button(frame_acte, font = NORMAL_FONT, text = "Emite acte.", command = self.emite_acte)
emite_acte.grid(row = row_i, column = 1, padx = 15, pady = 30, ipadx = 70, ipady = 10)
emite_acte.configure(bg = '#218838', fg = '#FFFFFF')
buton_cancel = tk.Button(frame_acte, font = NORMAL_FONT, text = "Cancel", command = lambda: self.destroy())
buton_cancel.grid(row = row_i, column = 0, padx = 15, pady = 30, ipadx = 70, ipady = 10)
buton_cancel.configure(bg = "red", fg = '#FFFFFF')
def emite_acte(self):
print(self.cal.get_date().strftime("%d/%m/%y"))
print(self.winfo_height(), self.winfo_width())
if __name__ == "__main__":
root = tk.Tk()
app = ConstituireDosar(root)
app.protocol("WM_DELETE_WINDOW", root.destroy)
root.withdraw()
root.mainloop()
I tried some options that I saw on the forum, in another file they worked fine but when I tried to implement it in the project itself the checkbutton is still unclickable and it doesn't display the images either. tkinter checkbutton different image I tried to replicate Bryan's answer, but no luck there. Also didn't receive any console error message.
As #furas pointed in the comments above, the problem got fixed with keeping the images as member variables of the class, also the button became clickable after removing the self.toggle(var) command from checkbutton
the following is working first pass around. Select file/s, activate the view button and def, view files. all good.
When trying to select another file/s, during the selection process, the GUI closes abruptly.
I tried to figure out of the variable needs to be reset, but that did not change.
after all the imports:
root = tk.Tk()
root.title("Motion GUI")
root.minsize(width=1000, height=700)
root.maxsize(width=1400, height = 900)
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N,W,E,S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0,weight=1)
WidgetFrame = ttk.Frame(mainframe, borderwidth=2,relief='ridge',height = 60)
WidgetFrame.grid(column=0,row=0, sticky="E,W")
def CreateWidgets():
link_Label = Label(WidgetFrame, text ="Select File(s): ", bg = "#E8D579")
link_Label.grid(row = 1, column = 0, pady = 5, padx = 5)
WidgetFrame.sourceText = Entry(WidgetFrame, width = 50, textvariable = sourceLocation)
WidgetFrame.sourceText.grid(row = 1, column = 1, pady = 5, padx = 5, columnspan = 2)
source_browseButton = Button(WidgetFrame, text ="Browse", command = SourceBrowse, width = 15)
source_browseButton.grid(row = 1, column = 3, pady = 5, padx = 5)
viewButton = Button(WidgetFrame, text ="View File(s)", command = ViewFile, width = 15)
viewButton.grid(row = 3, column = 0, pady = 5, padx = 5)
def SourceBrowse():
WidgetFrame.files_list = list(filedialog.askopenfilenames(initialdir ="/mnt/data/Motion_Data/Motion_Clips",title="Press shift key plus Left mouse click to select multiple files"))
def ViewFile():
# plays all selected files one by one, keeps speed selected in 1st clip unless changed..
files_list = WidgetFrame.files_list
for f in files_list:
player.playlist_append(f)
player.playlist_pos = 0
player.wait_for_playback
sourceLocation = StringVar()
destinationLocation = StringVar()
file_list = StringVar()
CreateWidgets()
root.mainloop()
What am I missing?
here is the full code with all the buttons and functions. BTW, all the other Buttons and Functions do work without problems (that is: Copy/Move/Delete):
#!/usr/bin/python3
import os
import shutil
import tkinter as tk
from tkinter import *
from tkinter import filedialog, messagebox
from tkinter import ttk
import webbrowser
if os.environ.get('DISPLAY','') == "":
print('no display found.Using :0.0')
os.environ.__setitem__('DISPLAY',':0.0')
##### MPV.py HAS TO BE copied into the directory which imports mpv ######
import mpv
player = mpv.MPV(ytdl=True,input_default_bindings=True,input_vo_keyboard=True,osc=True)
media = open('mPlaylist.u3e', 'r').read().splitlines()
# Creating object of tk class
root = tk.Tk()
root.title("Motion GUI")
root.minsize(width=1000, height=700)
root.maxsize(width=1400, height = 900)
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N,W,E,S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0,weight=1)
WidgetFrame = ttk.Frame(mainframe, borderwidth=2,relief='ridge',height = 60)
WidgetFrame.grid(column=0,row=0, sticky="E,W")
# Setting the title and background color disabling the resizing property
root.geometry("830x420")
root.title("View/Copy/Move/Delete mkv's")
root.config(background = "gray")
def CreateWidgets():
WidgetFrame.link_Label = Label(WidgetFrame, text ="Select File(s): ", bg = "#E8D579")
WidgetFrame.link_Label.grid(row = 1, column = 0, pady = 5, padx = 5)
WidgetFrame.sourceText = Entry(WidgetFrame, width = 50, textvariable = sourceLocation)
WidgetFrame.sourceText.grid(row = 1, column = 1, pady = 5, padx = 5, columnspan = 2)
WidgetFrame.source_browseButton = Button(WidgetFrame, text ="Browse", command = SourceBrowse, width = 15)
WidgetFrame.source_browseButton.grid(row = 1, column = 3, pady = 5, padx = 5)
WidgetFrame.destinationLabel = Label(WidgetFrame, text ="Select The Destination : ", bg ="#E8D579")
WidgetFrame.destinationLabel.grid(row = 2, column = 0, pady = 5, padx = 5)
WidgetFrame.destinationText = Entry(WidgetFrame, width = 50, textvariable = destinationLocation)
WidgetFrame.destinationText.grid(row = 2, column = 1, pady = 5, padx = 5, columnspan = 2)
WidgetFrame.dest_browseButton = Button(WidgetFrame, text ="Browse", command = DestinationBrowse, width = 15)
WidgetFrame.dest_browseButton.grid(row = 2, column = 3, pady = 5, padx = 5)
WidgetFrame.viewButton = Button(WidgetFrame, text ="View File(s)", command = ViewFile, width = 15)
WidgetFrame.viewButton.grid(row = 3, column = 0, pady = 5, padx = 5)
WidgetFrame.copyButton = Button(WidgetFrame, text ="Copy File", command = CopyFile, width = 15)
WidgetFrame.copyButton.grid(row = 3, column = 1, pady = 5, padx = 5)
WidgetFrame.moveButton = Button(WidgetFrame, text ="Move File", command = MoveFile, width = 15)
WidgetFrame.moveButton.grid(row = 3, column = 2, pady = 5, padx = 5)
WidgetFrame.moveButton = Button(WidgetFrame, text ="Delete File(s)", command = DeleteFile, width = 15)
WidgetFrame.moveButton.grid(row = 3, column = 3, pady = 5, padx = 5)
WidgetFrame.MotionButton = Button(WidgetFrame, text="IP Streams",command=MotionHTTP, font="LUCIDA 12")
WidgetFrame.MotionButton.grid(row=3,column=5,pady=5,padx=5)
WidgetFrame.exitButton = Button(WidgetFrame, text="Quit", command=root.destroy, font="LUCIDA 12 bold")
WidgetFrame.exitButton.grid(row = 3, column = 6,pady = 5, padx = 5)
def MotionHTTP():
webbrowser.open("http://192.168.0.26:8080")
def SourceBrowse():
WidgetFrame.files_list = list(filedialog.askopenfilenames(initialdir ="/home/rainer/Videos",title="Press shift key plus Left mouse click to select multiple files"))
files_list = []
WidgetFrame.sourceText.insert('1', WidgetFrame.files_list)
def DestinationBrowse():
destinationdirectory = filedialog.askdirectory(initialdir ="/mnt/data/Motion_Data/Motion_Clips")
WidgetFrame.destinationText.insert('1', destinationdirectory)
def ViewFile():
# plays all selected files one by one, keeps speed selected in 1st clip unless changed..
files_list = WidgetFrame.files_list
for f in files_list:
print(f)
player.playlist_append(f)
player.playlist(files_list)
#player.playlist_pos = 0
player.wait_for_playback
playlist.close()
def CopyFile():
files_list = WidgetFrame.files_list
destination_location = destinationLocation.get()
# Looping through the files present in the list
shutil.copy(f, destination_location)
def MoveFile():
files_list = WidgetFrame.files_list
destination_location = destinationLocation.get()
for f in files_list:
shutil.move(f, destination_location)
def DeleteFile():
files_list = WidgetFrame.files_list
for f in files_list:
os.remove(f)
# Creating tkinter variable
sourceLocation = StringVar()
destinationLocation = StringVar()
files_list = StringVar()
#destinationLocation = StringVar(value='/home/rainer/Music')
#file_list = StringVar()
# Calling the CreateWidgets() function
CreateWidgets()
# Defining infinite loop
root.mainloop()
I have the position data in the SQLite DB(employee_position). As well it's fetching the data for the position:
self.employee_position = employee_info[0][8]
However, I'm not able to insert the data. How can I insert the data into the combobox?
It does work for other fields like Entry:
#Entry
self.email_entry.insert(0, self.employee_email)
self.email_entry.config(state = 'disabled')
# Position
self.available = self.employee_position
self.position_lbl = Label(self.centerFrame, text = 'Position:', fg = '#b3b3b3', bg = '#121212')
self.position_lbl.grid(row = 7, column = 0, sticky = W, columnspan = 2, padx = 5)
self.position = ttk.Combobox(self.centerFrame, values=self.available, width = 27)
self.position.config(state = 'disabled')
self.position.grid(row = 7, column = 1, sticky = W, columnspan = 2, pady = 5)
Solution:
# Position
self.available = [self.employee_position]
self.position_lbl = Label(self.centerFrame, text = 'Position:', fg = '#b3b3b3', bg = '#121212')
self.position_lbl.grid(row = 7, column = 0, sticky = W, columnspan = 2, padx = 5)
self.position = ttk.Combobox(self.centerFrame, values=(self.available), width = 27)
self.position.set(self.employee_position)
self.position.config(state = 'disabled')
self.position.grid(row = 7, column = 1, sticky = W, columnspan = 2, pady = 5)
I am trying to do a onscreen keyboard using python 3.5. However when I try to run the program, only the space button appear but not the rest.
buttons = [
'q','w','e','r','t','y','u','i','o','p','<-','7','8','9','-',
'a','s','d','f','g','h','j','k','l','[',']','4','5','6','+',
'z','x','c','v','b','n','m',',','.','?','&','1','2','3','/',
'SPACE',
]
label1 = Label(Keyboard_App,text=("\n")).grid(row = 0,columnspan = 1)
entry = Entry(Keyboard_App, width = 128)
entry.grid(row = 1, columnspan = 15)
varRow = 2
varColumn = 0
for button in buttons:
command = lambda x = button: select(x)
if button != "Space":
tkinter.Button(Keyboard_App, text = button, width = 5,bg = "#000000",fg = "#ffffff",
activebackground = "#ffffff", activeforeground = "#000000", relief = 'raised',padx = 4,
pady = 4, bd = 4, command = command).grid(row = varRow, column = varColumn)
if button == "Space":
tkinter.Button(Keyboard_App, text = button, width = 60, bg = "#000000",fg = "#ffffff",
activebackground = "#ffffff", activeforeground = "#000000", relief = 'raised',
padx = 4, pady = 4, bd = 4, command = command).grid(row = 6, columnspan = 16)
I'm starting to code with Python and on my first application I have reached a brick wall. Any help on why this code is not displaying the widgets will be greatly appreciated!
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def _init_(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.header_frame, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 0, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp()
root.mainloop()
if __name__ == '__main__':
main()
Everytime I launch the code I get a blank tkinter window.
This had a few problems.
You had an _init_ method, not an __init__ method, so the created object wasn't being initialized.
You have to send the root tkinter object to the application, with app = ImprintPlusApp(root).
You had a self.header_frame once instead of self.frame_header.
You had a columnspan = 0 (which is invalid) instead of columnspan = 1 (which doesn't really need to be specified).
I've made the above changes in the code below. It may still need debugging, as I don't know exactly what design you had in mind.
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def __init__(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.frame_header, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 1, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp(root)
root.mainloop()
if __name__ == '__main__':
main()