I want to select one of installed printer on my computer and print through it but my combobox doesn't display the printers on my machine but rather print to my terminal in my IDE .
Have been trying this for days with arriving at the solution to do this.Have installed the win32print module to after reading about it.This my code below:
from tkinter import *
from tkinter import ttk
import win32print
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,
textvariable=installed_printer).pack()
BUTTON = ttk.Button(pt, text="refresh",
command=installed_printer).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10)
def INFO():
print(T2.get("1.0", END))
Print_Button = Button(root, text ="Print", command =
INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
How can i achieve this as i want to print the content in my Text box with tkinter framework.
Is this what you wanted to create?
from tkinter import *
from tkinter import ttk
import win32api
import win32print
import tempfile
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
printerdef = ''
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
var1 = StringVar()
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,textvariable=var1)
print_list = []
printers = list(win32print.EnumPrinters(2))
for i in printers:
print_list.append(i[2])
print(print_list)
# Put printers in combobox
PRCOMBO['values'] = print_list
PRCOMBO.pack()
def select():
global printerdef
printerdef = PRCOMBO.get()
pt.destroy()
BUTTON = ttk.Button(pt, text="Done",command=select).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10, wrap=WORD)
def INFO():
printText = T2.get("1.0", END)
print(printText)
print(printerdef)
filename = tempfile.mktemp(".txt")
open(filename, "w").write(printText)
# Bellow is call to print text from T2 textbox
win32api.ShellExecute(
0,
"printto",
filename,
'"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
Print_Button = Button(root, text ="Print", command=INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
Related
I have changed everything on other answers but nothing works.
from tkinter import *
import tkinter as tk
import tkinter
import pynput
from pynput.keyboard import Key, Listener
from tkinter import filedialog
charCount = 0
keys = []
press_value = 0
root = Tk()
my_menu = Menu(root)
root.config(menu=my_menu)
def label1(root):
label = tkinter.Label(root, text = "correct")
label.pack()
def pressOn():
button_1.configure(fg = "Green", text = "ON")
def pressOff():
button_1.configure(fg = "red", text = "OFF")
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pack(fill=BOTH, expand=1)
def save_location():
location_window = Tk()
var = StringVar()
var.set('No Folder Selected')
locationLabel = Label(location_window, textvariable=var.get())
locationLabel.place(x=70,y=20)
location_window.update()
def browse_button():
filename = filedialog.askdirectory()
print(filename)
var = filename
button2 = Button(location_window, text="Browse", command=browse_button).grid(row=1, column=0)
location_window.title('Save Location')
location_window.iconbitmap('C:/Users/Gaming/Downloads/floppydisk.ico')
location_window.geometry('250x100')
location_window.mainloop()
file_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New...", command=label1)
file_menu.add_command(label="Exit", command=root.quit)
#Create an edit menu item
edit_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Save Location", command=save_location)
edit_menu.add_command(label="Copy", command=label1)
def buttonPress():
global press_value
press_value = press_value + 1
if (press_value % 2) == 0:
pressOff()
else:
pressOn()
button_1 = tkinter.Button(text="OFF", width = '10', height = '10', fg = 'red', command = buttonPress)
button_1.pack(side = 'bottom')
If you click 'edit' and then'save location'. It pops up with a box but should show a label about the directory people can choose by picking the browse button. It is not working though, the label is not showing. Thanks for everyone's help in advance.
what I want to do, is to open from the root window a toplevel window in which I have series of entry widgets, modify the entries and close the window. I found a code in one of the posts and modified it to fit my need. The code works only the first time I open the toplevel window, but after that it opens the toplevel window without the entry fields! I don't understand what is happening!! Can anyone help please? I am quite new to python. Here is the code:
from tkinter import *
root = Tk()
entry_list = []
def openwindow():
window = Toplevel()
window.title("Data")
entry_list.clear()
for i in range(10):
entry_list.append(Entry(window))
entry_list[i].grid()
def update_entry_fields():
for i in entry_list:
i.delete(END)
i.insert(0, "")
print(float(entry_list[0].get()))
def closewindow():
window.withdraw()
savebtn = Button(window, text="Save & print", command = update_entry_fields)
closebtn = Button(window, text="Close", command=closewindow)
savebtn.grid()
closebtn.grid()
def printout():
print(float(entry_list[0].get()))
printbtn = Button(root, text="Test print", command = printout)
printbtn.grid()
openbutton = Button(root, text="open data sheet", command=openwindow)
openbutton.grid()
root.mainloop()
Here is the solution that at least i was looking for.
from tkinter import *
root = Tk()
entry_list = []
p = [5, 6, 7, 8, 9]
def openwindow():
window = Toplevel()
window.title("Data")
entry_list.clear()
for i in range(5):
v = DoubleVar()
entry_list.append(Entry(window, textvariable=v))
entry_list[i].grid()
v.set(p[i]) # set default entry values
def update_entry_fields():
for i in range(5):
p[i]=entry_list[i].get() # overwrite the entry
# test print from inside
print(p[i])
window.withdraw()
savebtn = Button(window, text="Save & close", command = update_entry_fields)
savebtn.grid()
window.mainloop()
# Test print from outside of function
def printout():
print(p[0])
printbtn = Button(root, text="Test print", command = printout)
printbtn.grid()
openbutton = Button(root, text="open data sheet", command=openwindow)
openbutton.grid()
#
root.mainloop()
good day! here's my code:
import tkinter as tk
namemass =["dev", "Dev1"]
self.entry_name = ttk.Entry(self)
self.entry_name.place(x=200, y=50)
btn_cancel = ttk.Button(self, text="cancel", command=self.destroy)
btn_cancel.place(x=300, y=800)
btn_ok = ttk.Button(self, text="ok")
btn_ok.place(x=320, y=170)
so, i have 2 buttons and enter box. I want the program to get the text from the enter box and if namemass list have that inside, then exit. in console program i would code it like that:
name = input()
namemass = ["dev", "Dev1"]
if name in namemass:
import sys
sys.exit()
else:
..........
how to do it using tkinter? thank you in advance!
To fetch the current entry text, use the get method:
current_text = Entry.get()
in your example you can just:
from tkinter import *
import sys
def destroy():
name = entry_name.get()
if name in namemass:
sys.exit()
root = Tk()
namemass = ["dev", "Dev1"]
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok")
btn_ok.pack()
root.mainloop()
Much easier for Python 3.8, using Walrus. Just add the function for _ok. And add command in btn_ok.
from tkinter import *
import sys
namemass = ["dev", "Dev1"]
def destroy():
#sys.exit()
root.destroy()
def _ok():
if(name_in_list := entry_name.get()) in namemass:
sys.exit()
root = Tk()
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok", command=_ok)
btn_ok.pack()
root.mainloop()
I have this render_gui function in Python.
def render_gui():
global root
global prev_key
global listbox, label1, entry1
prev_key = 0
root = tk.Tk()
root.title('Server Chat Application')
scroll = Scrollbar(root)
scroll.pack(side = "right" , fill= "y")
listbox = Listbox(root, width=80, height=30)
listbox.grid(row=1,column=1, columnspan=5,rowspan=3)
scroll.config(command = listbox.yview)
label1 = ttk.Label(root, text='Message Entry Box : ')
label1.grid(row=4,column=1)
entry1 = ttk.Entry(root, width=60)
entry1.grid(row=4, column=2)
root.geometry('490x520')
#print('before main loop')
root.bind('<KeyPress>', onKeyPress)
#print('after main loop')
root.mainloop()
It was throwing an error after I added the scrollbar thing. How will I encorporate a vertical and horizontal scrollbar in my listbox. Thanks.
UPDATE:
Below is the complete code. I have edited it and omit the pack thing replace it with grid function but the scrollbar wasn't showing. How am I gonna deal with this?
import os
import signal
import socket
import time
import threading
import keyboard
from threading import Thread
import tkinter as tk
from tkinter import ttk
from tkinter import *
import webbrowser
def onKeyPress(event):
global prev_key
global root
global listbox, label1, entry1
if(event.keycode == 13):
print(Entry.get(entry1))
msg = Entry.get(entry1)
if len(str.encode(msg)) > 0:
client.send(str.encode("\nserver > " + msg))
listbox.insert(END, "server > " + msg)
entry1.delete(0,END)
if(event.keycode == 88) and (prev_key == 17):
root.destroy()
try:
raise client.send(str.encode("***Server has been shutdowned***"))
except:
print ("You are not yet connected to any client to send shutdown notice.")
sys.exit()
os.kill(os.getpid(), signal.SIGUSR1)
prev_key = event.keycode
def render_gui():
global root
global prev_key
global listbox, label1, entry1
prev_key = 0
root = tk.Tk()
root.title('Server Chat Application')
scroll = Scrollbar(root)
#scroll.pack(side = "right" , fill= "y")
scroll.grid(row=0, column=10, rowspan=10, sticky='ns')
listbox = Listbox(root, width=80, height=30)
listbox.grid(row=1,column=1, columnspan=5,rowspan=3)
scroll.config(command = listbox.yview)
listbox.config(yscrollcommand=scroll.set)
label1 = ttk.Label(root, text='Message Entry Box : ')
label1.grid(row=4,column=1)
entry1 = ttk.Entry(root, width=60)
entry1.grid(row=4, column=2)
root.geometry('490x520')
#print('before main loop')
root.bind('<KeyPress>', onKeyPress)
#print('after main loop')
root.mainloop()
if __name__ == "__main__":
Thread(target= render_gui).start()
class Login:
def __init__(self):
Label1 = Label(root,text = "Username")
Label2 = Label(root,text = "Password")
self.Entry1 = Entry(root)
self.Entry2 = Entry(root,show = "*")
Label1.grid(row=0)
Label2.grid(row=1)
self.Entry1.grid(row = 0,column = 1)
self.Entry2.grid(row = 1,column = 1)
root.minsize(width = 300,height = 80)
##new_window_button = Button(text="new window", command = ????)
##new_window_button.grid(columnspan = 2)
lgbutton = Button(text = "Login",command = self.ButtonClicked)
lgbutton.grid(columnspan = 2)
def ButtonClicked(self):
username = self.Entry1.get()
password = self.Entry2.get()
GetDatabase(username,password)
Currently this is what I have to create a window, however I want it to that when the new_window_button is clicked, the new page has its own widgets. I've used Toplevel before but it creates a child window without the widgets. Instead, the widgets are added to the parent window.
Judging by the comments it looks as though you are struggling with declaring the correct parent for widgets.
When a widget is declared the first parameter passed in to it is it's parent. For example:
Label(root, text="I'm in the root window.")
# ^ This is the parent
As opposed to:
Label(top, text="I'm in the top window.")
# ^ This is the parent
Please see a more fleshed out example below:
from tkinter import *
root = Tk()
top = Toplevel(root)
label1 = Label(root, text="I'm a placeholder in your root window.")
label2 = Label(top, text="I'm a placeholder in your top window.")
label1.pack()
label2.pack()
root.mainloop()
import tkinter
from tkinter import *
class LoginForm(Frame):
def __init__(self,master=None):
super().__init__(master)
self.pack()
self.createWidget()
def createWidget(self):
self.lblEmailId=Label(self,text="Email Id")
self.lblEmailId.grid(row=0,column=0)
self.varEmailid=StringVar()
self.txtEmailId=Entry(self,textvariable=self.varEmailid)
self.txtEmailId.grid(row=0,column=1)
self.txtEmailId.bind("<KeyRelease>",self.key_press)
self.lblPassword = Label(self, text="Password")
self.lblPassword.grid(row=1, column=0)
self.varPassword=StringVar()
self.txtPassword= Entry(self, textvariable=self.varPassword)
self.txtPassword.grid(row=1, column=1)
self.btnLogin=Button(self,text="Login")
self.btnLogin.grid(row=2,column=1)
self.btnLogin.bind("<Button-1>",self.btnLogin_click)
def btnLogin_click(self,event):
self.varPassword.set(self.varEmailid.get())
LoginWindow=Toplevel()
def key_press(self,event):
self.varPassword.set(self.varEmailid.get())
root=Tk()
fromLogin=LoginForm(root)
root.mainloop()