I am making a server with Tkinter where it asks for the IP address you want to start the server on. when you jit enter it's supposed to close the window and start the server but the window doesn't close it just crashes(the server also starts though).
my code:
#!/usr/bin/env python3
import socket, threading, sys
import tkinter as tk
def sub(self):
global ip
ip = e1.get()
rw.quit()
rw = tk.Tk()
rw.title("IP")
rw.configure(bg="grey14")
rw.geometry("250x50")
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
e1 = tk.Entry(rw)
e1.bind("<Return>", sub)
e1.insert(0, IPAddr)
e1.pack(side=tk.LEFT)
b1 = tk.Button(rw, text="Submit", command=sub).pack(side=tk.RIGHT)
rw.mainloop()
please help!
(the server code is left out because StackOverflow says I'm not allowed to have that much code and this little text, but basically it starts another loop that accepts the clients)
You should use this command instead:
rw.destroy()
rw.quit() just bypasses the rw.mainloop() so that rw.mainloop() will still be running in the background. rw.destroy() stops it.
You are using sub(self)and on your Buttonyou have written just command=sub
So you have to write their
self.b1=tk.Button(rw,text="Submit",command=sub).pack(side=tk.RIGHT)
It's working I have run it
Related
i'm new in the python language and have been learning and working with it for 2 days now.
I'm writing a code to send grbl files to my cnc-machine.
my code:
def grbl_sturing(Gcode_file):
print('running')
lbl_Running = Label(root, text="running")
lbl_Running.grid(row=0, column=2)
#Grbl setup
poort = serial.Serial('com11',115200)
code = open(Gcode_file,'r');
poort.write(b'\r\n\r\n')
time.sleep(2)
poort.flushInput()
#sturing
for line in code:
l = line.strip()
print ('Sending: ' + l)
poort.write(l.encode() + b'\r\n')
grbl_out = poort.readline()
print (' : ' + str(grbl_out.strip()))
#Grbl afsluiten
code.close()
poort.close()
So when i press a button in my tkinter window i go to this fucntion. My intensions where to let me know in a label and in my cmd that the program is sending/running.
But when i press this button my cmd show this:
running
Sending: $H
: b'ALARM:9'
Don't mind the alarm its because the cnc-machine isn't powered.
In the cmd it works like itended but when i look in my tkinter window it runs first and when its done it shows me that it is running. Why does it do this and how can i fix it? thank you in advance.
ps(sorry for my bad English)
So, what is happening here is that you are creating the label, but the GUI isn't updating until later, to make it update in that order you must use the line:
TK.update()
Where TK is your tkInter variable to force the interface to update at that point, instead of waiting for the main loop.
Good afternoon thank you all who look at my issue,
I am building a script to do initial configuration on switches through console port, I can make a connection to the console port the issue comes when building a GUI in TKINTER.
I want the gui to connect through a specified some port when the button is pressed and when the connection is made make a light(using canvas) go green showing a successful connection went through.
My issue is getting the light to change to green and stay when a connection is made I have tried
my initally also tried to use global then realized the window loop constantly set it back to red
nested while loop--- breaks Tkinker
importing a file I created called variableset which stores variable to set green but since it constantly has a new instance it just sets the variable in tinker back to red.
any help would be greatly appreciated
GUI CODE
import tkinter as tk
from tkinter import *
import connect
import variableset
setting = variableset.setting
window = tk.Tk()
window.title("Network Wizard 1")
window.geometry('300x500')
# setting =tk.IntVar()
# setting.set(variableset.setting)
#serial port pick the right one
serialportlabel = tk.Label(text="COM Number")
serialport = tk.Entry(width= 7)
serialportlabel.pack()
serialport.pack()
#color alerting!! red bad
alert = Canvas(window, width=50, height=20)
alert.pack()
if setting == 0:
a=alert.create_rectangle(5, 0, 50, 50, fill='red')
else:
a=alert.create_rectangle(5, 0, 50, 50, fill='green')
# #connection part woop woop
connection = tk.Button(text="connect", command = lambda: bus())
connection.pack()
# #firmwarecheck
# firmwarecheck = tk.Button(text="Firmware check")
# firmwarecheck.pack()
# #firmware update
# firmwareupdate= tk.Button(text="Firmware update")
# firmwareupdate.pack()
# #software update
# software = tk.Button(text="software update")
# connect.pack()
# #vmlans
# vlanupdate = tk.Button(text="Vlanupdate")
# vlanupdate.pack()
# disconnect = tk.Button(text="disconnect")
# disconnect.pack()
# qut = tk.Button(text="quite")
# qut.pack()
def bus():
global ser
ser = connect.connect(serialport.get())
global setting
setting = variableset.initial
# def firmware(ser):
# if ser.isOpen() == true :
window.mainloop()
Connect code
import serial
import time
import sys
#connect
def connect(com):
ser = serial.Serial(
port = com, #COM
baudrate=9600,
parity='N',
stopbits=1,
bytesize=8,
timeout=8
)
ser.isOpen()
print(ser.name)
#set variables
enter = str.encode('\r\n') #enter
user = str.encode('admin#sytem\r\n') #default user name
pwd = str.encode('\r\n') #defualt password
qut = str.encode('quit\r')
time.sleep(1.0)
# ser.inWaiting()
ser.write(enter) #promt login
time.sleep(0.5)
ser.write(user) #enter user name
time.sleep(0.5)
ser.write(pwd) #enter password
time.sleep(0.5)
ser.write(enter)
time.sleep(0.5)
ser.write(enter)
time.sleep(0.5)
ser.write(str.encode("sytem\r\n"))
time.sleep(0.5)
ser.write(qut)
ser.write(qut)
input_read = ser.read(500)
input_read = input_read.decode("utf-8","ignore")
print(input_read)
ser.close()
return ser
def write(ser):
ser.write(str.encode(''+'\r\n'))
def disconnect(ser):
ser.write(str.encode('quit\r\n'))
time.sleep(.2)
ser.write(str.encode('quit\r\n'))
time.sleep(.2)
ser.write(str.encode('quit\r\n'))
time.sleep(.2)
ser.close()
Variableset Code
global setting
setting = 0
def initial():
global setting
setting = 1
return setting
def unset():
global setting
setting = 0
return setting
Any help greatly appreciated
Your if-else statement only runs once, before the setting variable has been set, as far as we can tell. It's not in a loop or a function that gets called from somewhere else. What exactly is the problem you're having with the code that you posted? The issues you described seem to relate to a loop setting it back to red in a different version of the code.
In any event, I suspect that your problem is trying to use infinite loops to keep checking the setting, which prevents the tkinter mainloop() from running, and therefore blocks the GUI from updating. If so, the best method to fix it is probably to change your code for "check the setting and then change the color" into its own function, which gets called for the first time at the end of your connect function. Then, the end of the check setting function should schedule itself to be run after a time delay using the tkinter after() method, which is non-blocking (asnychronous) and allows the mainloop() to keep running. Alternative methods include a separate thread to run the check-setting code, or using the tkinter update() method, but after() is easiest.
Note that your sleep() functions in the connect code will also block the mainloop while they're running. I'm also not clear what you're trying to do with the variableset code; it appears to set the setting to 1 (aka green light) when you call initial(), regardless of the actual status on the serial port.
hey guys I been trying to host a local server on port 22222 and when someone open it on the browser I get a msgbox saying yes / no - if you click yes it will accept the connection and show index.html basically, if you click no it will return nothing or something, anyway it works perfectly BUT
I'm trying to trigger a second msgbox after you click on the first one with a delay(after command), when you access the first time and click yes, it serves the page but the Established msg does not show up, if you refresh the page than it retriggers the Established msg and than ask again if you want to accept the connection (Bug Alert lol)
basiclly you need to run this code open 127.0.0.1:22222, click yes, than you will not see the its_ok msgbox, unless you do all this again
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler, test as Brain_Link
import tkinter
import tkinter.messagebox as mbox
window = tkinter.Tk()
window.wm_withdraw()
window.attributes("-topmost", True)
def Start_Brain_Link(*args):
Brain_Link(*args, port=22222)
def its_ok():
mbox.showinfo('A.I','Brain-Link Established!')
def its_bad():
mbox.showinfo('A.I','Brain-Link Attemp Blocked!')
class CORSRequestHandler(SimpleHTTPRequestHandler):
def end_headers (self):
if mbox.askquestion("Warning!", self.client_address[0]+" Requested Brain-Link!", icon='warning') == 'yes':
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
window.after(1000,its_ok)
else:
window.after(1000,its_bad)
if __name__ == '__main__':
Start_Brain_Link(CORSRequestHandler, HTTPServer)
I am doing my Graduation Project,and i meet some problem.
I have search for a long time and read some documents. But no use.
Please help or try to give some ideas how to achieve this.
I want to achieve a function that get local ip and show it by using label when entering the interface.I don't understand how to deliver a variable from the"get_ip_address" to textvariable.
My os is Linux,python version is 2.7.
Here is some code:
import fcntl,struct,Tkinter,socket
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(),
0x8915,struct.pack('256s',
ifname[:15])
)[20:24])
top = Tkinter.Tk()
top.geometry('400x300+200+300')
ip_address = Tkinter.StringVar()
ip_address.set(get_ip_address)
icon = top.iconbitmap('#/root/Downloads/python/sdju.xbm')
top.tk.call('wm','iconphoto',top._w,icon)
lable1 = Tkinter.Label(top,textvariable = ip_address)
lable1.pack()
top.mainloop()
Try the following.
You are using ip_address.get(get_ip_address) getter functions generally take no arguments and any arguments given here will produce an error. What you want to do is set the value. So instead you need to call ip_address.set(get_ip_address).
The next issue is that you don't call get_ip_address you pass a reference to the function. So make sure you call it and the string will be set to it's return value and not a string representation of the function itself. You should pass the name of the network interface, you want the ip address for.
So ip_address.set(get_ip_address) becomes ip_address.set(get_ip_address('lo')).
complete code:
import fcntl, struct, Tkinter, socket
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915,struct.pack('256s', ifname[:15]))[20:24])
top = Tkinter.Tk()
top.geometry('400x300+200+300')
ip_address = Tkinter.StringVar()
ip_address.set(get_ip_address('lo'))
icon = Tkinter.PhotoImage(file='/root/Downloads/python/sdju.xbm')
top.tk.call('wm', 'iconphoto', top._w, icon)
lable1 = Tkinter.Label(top, textvariable=ip_address)
lable1.pack()
top.mainloop()
Okay, time for another question/post...
So currently i am trying to develop a simple python program that has a webkit/ webpage view and a serial port interface.. Not that it should matter, but this is also running on a raspberry pi.
The following code works fine.. But it will freeze the system as soon as i uncomment the serial port line that you can see commented out.
The day has been long and this one for some reason has my brain fried.. Python is not my strongest point, but mind you this is just a quick test script for now... Yes i have used google and other resources...
#!/usr/bin/env python
import sys
import serial
import threading
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
sURL = ""
sURL2 = ""
objSerial = serial.Serial(0)
def SerialLooper():
global objSerial
if objSerial.isOpen() == True:
print("is_responding")
#objSerial.write("is_responding")
time.sleep(10)
SerialLooper()
class TestCLASS(object):
def __init__(self):
global sURL
global sURL2
global objSerial
objSerial = serial.Serial(0)
sURL = "http://localhost/tester"
app = QApplication(sys.argv)
webMain = QWebView()
webMain.loadFinished.connect(self.load_finished)
webMain.load(QUrl(sURL))
webMain.show()
thread = threading.Thread(target=SerialLooper)
thread.start()
sys.exit(app.exec_())
def load_finished(boolNoErrors):
global sURL
print("Url - " + sURL)
#something here
#something else here
newObjClass = TestCLASS()
EDIT
Futher on this, it appears its not the multithreading but the serial.write()
It has been a while since I used serial, but IIRC it is not threadsafe (on Windows at least). You are opening the port in the main thread and performing a write in another thread. It's a bad practice anyway. You might also consider writing a simple single-threaded program to see if the serial port is actually working.
PS Your program structure could use some work. You only need one of the global statements (global objSerial), the rest do nothing. It would be better to get rid of that one, too.
And the recursive call to SerialLooper() will eventually fail when the recursion depth is exceeded; why not just use a while loop...
def SerialLooper():
while objSerial().isOpen(): # Drop the == True
# print something
# write to the port
# Sleep or do whatever