I'm making a GUI with python and tkinter That prompts user the Mac Address of his pc and asks for a code The Python snippet i have used for retrieving the MAc address is :
import uuid
def get_mac():
mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac = ''.join(mac_num[i : i + 2] for i in range(0, 11, 2))
return mac
x= get_mac()
print x
I have also made a gui containing the two fields as shown below
However when i execute the python snippet the mac address is displayed outside the python gui and in the python shell, how can i make the mac address appear in the space provided in the GUi itself
Here is the code for the gui:
from Tkinter import *
from ttk import *
root =Tk()
def show_form():
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
b = Button(bottomFrame,text="ACTIVATE",command=lambda: show_call_back(root))
b1 = Button(bottomFrame, text="TRIM")
b2 = Button(bottomFrame, text="OVERLAY")
b3 = Button(bottomFrame, text="MERGE")
b.pack(side=RIGHT,padx=8,pady=26)
b1.pack(side=LEFT, padx=8, pady=26)
b1.config(state='disabled')
b2.pack(side=LEFT, padx=8, pady=26)
b2.config(state='disabled')
b3.pack(side=LEFT, padx=8, pady=26)
b3.config(state='disabled')
root.mainloop()
def show_call_back(parent):
top = Toplevel(parent)
top.geometry("250x200+600+250")
top.resizable(width=False, height=False)
top.title("Activation")
Label(top, text="Mac Address:",).grid(row=0, sticky=W, padx=4)
Label(top, text="Code").grid(row=1, sticky=W, padx=4)
Entry(top).grid(row=1, column=1, sticky=E, pady=4)
Button(top, text="Submit", command=top.destroy).grid(row=2, column=1)
show_form()
root.mainloop()
After your last comment, the solution is quite simple: add a new Label to display the result of get_mac().
Solution - Add a Label in row=0 and text=get_mac().
hLbl = Label(top, text=get_mac(), bg='white', relief=SUNKEN, width = 15)
hLbl.grid(row=0, column=1, sticky=E, pady=4)
I have added bg='white' and relief=SUNKEN to a the same style as
an Entry. The extra width = 15 is to enlarge the size of the label.
Warning 1 - as #abccd comments, keep only one mainloop(), and place the root = Tk() after the function declaration.
Warning 2 - Instead of using root as a global variable in bottomFrame = Frame(root) of the function show_form(), add it as input parameter.
def show_form(my_root): # use my_root instead of global root
bottomFrame = Frame(my_root)
bottomFrame.pack(side=BOTTOM)
# also for the command parameter
b = Button(bottomFrame,text="ACTIVATE",command=lambda: show_call_back(my_root))
...
And call:
root = Tk()
show_form(root)
root.mainloop()
EDIT -------
Output - here is what I get under Python 3.5.0
Related
I'm trying to build a very simple program in Python and Tkinter that allows the user to input people's names by keyboard and then a button is commanded to select a person from the list at random and show it in a tk.Label object.
My problem is once I run the root.mainloop(), I can add names to the list but the list does not update with the new names.
This is the main code for the Tkinter to initialize
import tkinter as tk
from tkinter import filedialog, Text
import random
root = tk.Tk()
root.title('Millor persona del moment')
root.geometry("500x200")
root.configure(bg='black')
peopleList = []
tk.Label(root, text="Insertar participante: ",fg="#ff007f", bg='black').grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0, column=1)
addButton = tk.Button(root, text='AƱadir', padx=10, pady=5, fg="#ff007f", bg='black', command=addPerson)
addButton.grid(row=0, column=2)
while peopleList:
turnButton = tk.Button(root, text='Saca Tema', padx=10, pady=5, fg="#ff007f", bg='black', command=wordTurn(peopleList))
turnButton.grid(row=1, column=0)
nom = tk.StringVar()
nom.set('Comencem')
personSpeaking = tk.Label(root, textvariable=nom,fg="#ff007f", bg='black')
personSpeaking.grid(row=1, column=1)
root.mainloop()
And these are the functions I use
def addPerson():
peopleList.append(e1.get())
e1.delete(0,'end')
def wordTurn(peopleList):
person = random.choice(peopleList)
peopleList.remove(person)
nom.set(person)
command=wordTurn(peopleList)) calls the return value of wordTurn when the button is pressed, which is None and should raise an error. Use command=lambda peopleList=peopleList: wordTurn(peopleList)) instead.
I been searching for methods to copy text to clipboard or copy the results from Tkinter gui but idk if there is a command or something
here is my code for now here the result comes in a messagebox can i copy it to clipboard
import tkinter.messagebox
import string
import random
def qs_msgbbox(): # qs_msgbbox
tkinter.messagebox.showinfo("Info", "For customer support or tip or rating contact:"
"dghaily725#gmail.com\npress the button for generated pass\nmsg will appear then copy\nthe generated password")
def gen_pass(k=9): # gen_pass
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*"
password = ''
for i in range(9):
password += random.choice(char)
tkinter.messagebox.showinfo("Password", password)
root = Tk()
root.title("Password Generator")
lbl1 = Label(root, text="Generate Password", bd=2, relief=SUNKEN, height=5, width=50, bg='black', fg='white')
lbl1.configure(font=(70))
lbl1.grid(row=0, column=2)
lbl2 = Label(root, text='For more information press the Question mark', bd=2, relief=SUNKEN, fg='red')
lbl2.configure(font=(70))
lbl2.grid(row=0, column=0, pady=10)
btn1 = Button(root, text='Press to Generate', height=5, width=50, bg='grey', command=gen_pass)
btn1.configure(font=(70))
btn1.grid(row=1, column=2, padx=460, pady=50)
btn2photo = PhotoImage(file='question.png')
btn2 = Button(root, image=btn2photo, width=30, height=30, command= qs_msgbbox)
btn2.grid(row=0, column=1)
root.mainloop()
and also just a quick small question is it better to use classes or this form
Tkinter does have a function for that, simply just
from tkinter import Tk
root = Tk()
root.clipboard_clear()
root.clipboard_append("Something to the clipboard")
root.update() # the text will stay there after the window is closed
Hope I could help
Greets
The above answer is perfectly fine. Infact its the method to do it. I read the comments, He had mentioned that it could only take in string. That is completely false. It can also take in functions. For example..
import tkinter as tk
root = tk.Tk()
#creating a entry Widget.(Labels are fine as well)
entry = tk.Entry(root)
entry.pack()
#NOW if you want to copy the whole string inside the above entry box after you
typed in #
def copy ():#assign this function to any button or any actions
root.clipboard_clear()
root.clipboard_append(entry.get()) #get anything from the entry widget.
root.mainloop()
Hoping this was helpful
I have a GUI using Tkinter, it has a main screen and then when you press a button a popup window appears, where you select a checkbutton and then a email will get sent to you.
Not matter what I do, I cannot read the value of the checkbutton as 1 or True it always = 0 or False.
This is my code:
import tkinter as tk
from tkinter import *
import time
root = tk.Tk()
root.title('Status')
CheckVar1 = IntVar()
def email():
class PopUp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
popup = tk.Toplevel(self, background='gray20')
popup.wm_title("EMAIL")
self.withdraw()
popup.tkraise(self)
topframe = Frame(popup, background='gray20')
topframe.grid(column=0, row=0)
bottomframe = Frame(popup, background='gray20')
bottomframe.grid(column=0, row=1)
self.c1 = tk.Checkbutton(topframe, text="Current", variable=CheckVar1, onvalue=1, offvalue=0, height=2, width=15, background='gray20', foreground='snow', selectcolor='gray35', activebackground='gray23', activeforeground='snow')
self.c1.pack(side="left", fill="x", anchor=NW)
label = tk.Label(bottomframe, text="Please Enter Email Address", background='gray20', foreground='snow')
label.pack(side="left", anchor=SW, fill="x", pady=10, padx=10)
self.entry = tk.Entry(bottomframe, bd=5, width=35, background='gray35', foreground='snow')
self.entry.pack(side="left", anchor=S, fill="x", pady=10, padx=10)
self.button = tk.Button(bottomframe, text="OK", command=self.on_button, background='gray20', foreground='snow')
self.button.pack(side="left", anchor=SE, padx=10, pady=10, fill="x")
def on_button(self):
address = self.entry.get()
print(address)
state = CheckVar1.get()
print (state)
time.sleep(2)
self.destroy()
app = PopUp()
app.update()
tk.Button(root,
text="EMAIL",
command=email,
background='gray15',
foreground='snow').pack(side=tk.BOTTOM, fill="both", anchor=N)
screen = tk.Canvas(root, width=400, height=475, background='gray15')
screen.pack(side = tk.BOTTOM, fill="both", expand=True)
def latest():
#Other code
root.after(300000, latest)
root.mainloop()
The popup works perfectly, and the email will print when entered but the value of checkbox is always 0.
I have tried:
CheckVar1 = tk.IntVar() - No success
self.CheckVar1 & self.CheckVar1.get() - No success
Removing self.withdraw() - No success
I only have one root.mainloop() in the script, I am using app.update() for the popup window because without this it will not open.
I have checked these existing questions for solution and none have helped:
Self.withdraw - Can't make tkinter checkbutton work normally when running as script
Self.CheckVar1 - TKInter checkbox variable is always 0
Only one instance of mainloop() - Python tkinter checkbutton value always equal to 0
I have also checked very similar questions but I wasn't going to post them all.
Any help is appreciated.
The problem is that you have two root windows. Each root window gets its own internal tcl interpreter, and the widgets and tkinter variables in one are completely invisible to the other. You're creating the IntVar in the first root window, and then trying to associate it with a checkbutton in a second root window. This cannot work. You should always only have a single instance of Tk in a tkinter program.
because of variable scope
try to put CheckVar1 = IntVar() inside the class
use it with self like this
self.CheckVar1 = tk.IntVar() # object of int
self.CheckVar1.set(1) # set value
variable=self.CheckVar1 # passing to the checkbutton as parameter
state = self.CheckVar1.get() # getting value
I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop( )
This code is taking really long time to run, it has been almost 5 minutes!
Is it not possible to just run this snippet?
Can anybody tell me how to use Tkinter?
I am using jupyter notebook and python version 2.7. I would request a solution for this version only.
Your code is working just fine. Nevertheless for those using python3 module name has changed from Tkinter to tkinter all in lowercase. Edit the name and you're good to go!
In a nutshell.
python2:
from Tkinter import *
python3:
from tkinter import *
Look at the screenshot below
from Tkinter import *
def printData(firstName, lastName):
print(firstName)
print(lastName)
root.destroy()
def get_input():
firstName = entry1.get()
lastName = entry2.get()
printData(firstName, lastName)
root = Tk()
#Label 1
label1 = Label(root,text = 'First Name')
label1.pack()
label1.config(justify = CENTER)
entry1 = Entry(root, width = 30)
entry1.pack()
label3 = Label(root, text="Last Name")
label3.pack()
label1.config(justify = CENTER)
entry2 = Entry(root, width = 30)
entry2.pack()
button1 = Button(root, text = 'submit')
button1.pack()
button1.config(command = get_input)
root.mainloop()
Copy paste the above code into a editor, save it and run using the command,
python sample.py
Note: The above code is very vague. Have written it in that way for you to understand.
You can create a popup information window as follow:
showinfo("Window", "Hello World!")
If you want to create a real popup window with input mask, you will need to generate a new TopLevel mask and open a second window.
win = tk.Toplevel()
win.wm_title("Window")
label = tk.Label(win, text="User input")
label.grid(row=0, column=0)
button = ttk.Button(win, text="Done", command=win.destroy)
button.grid(row=1, column=0)
check it again the code is executing properly but u can't see that output in jupyter notebook itself u can see it in windows column like beside the chrome icons in toggle bar .I'm also confused initially check it once
Code:
from data import *
from tkinter import *
root = Tk()
root.title("python")
root.geometry("400x400")
label1 = Label(root, text="Type a thing:")
entry1 = Entry(root)
button_1 = Button(root, text="Sign In", command=execute1)
label1.grid(row=1, column=0, padx=(0,15))
entry1.grid(row=1, column=1)
button_1.grid(row=2, sticky=W)
root.mainloop()
I want to add margin to the window. Like adding margin in CSS.
I tried this:
root.grid(padx=20, pady=20)
But i'm getting this error:
TypeError: wm_grid() got an unexpected keyword argument 'padx'
I'm using Python 3.5, how can i do that?
You can not run this code:
root.grid(padx=20, pady=20)
Because both padx and pady options are used to add a padding to place around the widget in a cell. This means, you can use these two options for widgets positioned within the tkinter.TK() main window using the grid() method.
But for the main widget root itself you can not add any padding because a padding is added respectively to a tkinter.TK() cell.